Question :
In Python 3, operator.or_ is equivalent to the bitwise |
, not the logical or
. Why is there no operator for the logical or
?
Answer #1:
The or
and and
operators can’t be expressed as functions because of their short-circuiting behavior:
False and some_function()
True or some_function()
in these cases, some_function()
is never called.
A hypothetical or_(True, some_function())
, on the other hand, would have to call some_function()
, because function arguments are always evaluated before the function is called.
Answer #2:
The logical or is a control structure – it decides whether code is being executed. Consider
1 or 1/0
This does not throw an error.
In contrast, the following does throw an error, no matter how the function is implemented:
def logical_or(a, b):
return a or b
logical_or(1, 1/0)
Answer #3:
If you don’t mind the lack of short circuiting behaviour mentioned by others; you could try the below code.
all([a, b]) == (a and b)
any([a, b]) == (a or b)
They both accept a single collection (such as a list, tuple and even a generator) with 2 or more elements so the following is also valid:
all([a, b, c]) == (a and b and c)
For more details have a look at the documentation in question:
http://docs.python.org/py3k/library/functions.html#all