banhill banhill - 6 months ago 18
Python Question

In Python, what's the point of 'x or False' and 'False and x?

I'm working with web2py and I've been looking through the source code to get
some better understanding. Multiple times I've seen assignments like

# in file appadmin.py
is_gae = request.env.web2py_runtime_gae or False


If request.env.web2py_runtime_gae is true, then False does not matter. Either way the expression becomes false, if request.env.web2py_runtime_gae is false.

And also:

# in file appadmin.py
if False and request.tickets_db:
from gluon.restricted import TicketStorage


The second part of the and clause is never evaluated, because False and x always returns false.

So why would one do something like that?

Answer

Not quite like what you are assuming. Python evaluates conditions lazily, so if the value is known to satisfy the condition then the evaluation quits. See this example:

>>> None or False
False
>>> True or False
True
>>> 0 or False
False
>>> 'Value' or False
'Value'

The second one, as per lazy evaluation, will simply return False on that statement and the rest of the statements will not be evaluated. This can be a way to unconditionally disable that if statement.