hh32
hh32

Reputation: 170

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?

Upvotes: 2

Views: 109

Answers (2)

metatoaster
metatoaster

Reputation: 18938

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.

Upvotes: 5

Douglas Leeder
Douglas Leeder

Reputation: 53320

val = x or False

Ensures that val is actually 'False' (type 'bool') instead of Falsey values like 0 or "".

The second might be just a temporary disable for that condition?

The best place to investigate might be source control history?

Upvotes: 2

Related Questions