In Python 3, operator.or_ is equivalent to the bitwise |
, not the logical or
. Why is there no operator for the logical or
?
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.
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)
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
1 < 2
which would mean they are evaluated before. I always forget about the other meaning of or
. –
Icecap or
has only one meaning. Your answer provides only a clumsy way of using all/any
instead of &/|
-- not what the OP wants. –
Simson 5 or 6
has the result of 5
which isn't exactly boolean logic like True or False
. Good point it does look like I mean the functions don't short circuit, I'll edit the answer. However I think this could be useful if you wanted to pass around references to logical operators, I've found occasion to do the same thing with numerical operators before. –
Icecap © 2022 - 2024 — McMap. All rights reserved.
99 or 88
->99
butany([99, 88])
->True
(2)any
andall
DO short_circuit; givendef foo(): yield 1; yield 0; yield 1/0
thenall(foo())
->False
andany(foo))
->True
– Simson