1

I'm maintaining a large codebase and I found something that looks like this in my python code:

...
foo = bar(a, b, c) and foo
return foo
...

where foo is assigned a boolean, and is declared for the first time here. What does this mean/what purpose does this serve/what's going on here?

cerremony
  • 213
  • 2
  • 12

1 Answers1

5

Python does short circuit evaluation as C does.

This means in the "and" case, that the right side of the and is only evaluated if the left side effectively is True.

So your code is roughly equivalent to:

x = bar(a, b, c)
if x:
    foo = foo
else:
    foo = x
return foo

With the distinction of course, that the variable x is not used (since not needed).

The important fact to note here is, that for example if foo was set to "stringval" and bar(a,b,c) returns something that can be interpreted as True, than "stringval" will be returned. So unlike than in some other languages, a boolean expression can have a non-boolean result.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
Juergen
  • 12,378
  • 7
  • 39
  • 55