T.BJ
T.BJ

Reputation: 99

What does a trailing '==' after a variable assignment do in Python?

I recently stumbled across a line of code running on Python 3.7 which I hadn't seen before and couldn't find anything online as I didn't know what to search.

The context is similar to the following:

def some_function(some_var: bool = None):

    if some_var is None:
        some_var = os.environ.get("SOME_ENV_VAR", False) == "true"

What does the trailing double equals do here and why would it be used?

Upvotes: 0

Views: 85

Answers (2)

Right leg
Right leg

Reputation: 16730

There's no exotic syntax here. == is just a binary (as in "two arguments") operator, just like + or and.

You can see the line as a = b == c, and just like a = b + c would mean "Compute b + c and store that in a", this means "Compute b == c and store that in a, ie. put True in a if b is equal to c, False otherwise.

Upvotes: 0

wkl
wkl

Reputation: 79991

You can rewrite this piece of code as the following to see more clearly what it's doing.

if some_var is None:
   if os.environ.get("SOME_ENV_VAR", False) == "true":
       some_var = True
   else
       some_var = False

This line:

os.environ.get("SOME_ENV_VAR", False) == "true"

is a conditional check and then some_var would be assigned the result of the True/False check.

Upvotes: 3

Related Questions