banhill banhill - 1 year ago 74
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
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
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 Source

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
>>> True or False
>>> 0 or False
>>> 'Value' or False

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download