Why doesn't the operator module have a function for logical or?
Asked Answered
T

3

16

In Python 3, operator.or_ is equivalent to the bitwise |, not the logical or. Why is there no operator for the logical or?

Trinh answered 25/10, 2011 at 19:21 Comment(0)
D
23

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.

Dine answered 25/10, 2011 at 19:30 Comment(0)
S
9

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)
Suchlike answered 25/10, 2011 at 19:26 Comment(0)
I
2

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

Icecap answered 25/10, 2011 at 22:6 Comment(4)
-1 for TWO reasons: (1) 99 or 88 -> 99 but any([99, 88]) -> True (2) any and all DO short_circuit; given def foo(): yield 1; yield 0; yield 1/0 then all(foo()) -> False and any(foo)) -> TrueSimson
I should have been clearer but I meant each of the a, b and c to represent simple expressions with a boolean result such as: 1 < 2 which would mean they are evaluated before. I always forget about the other meaning of or.Icecap
Python or has only one meaning. Your answer provides only a clumsy way of using all/any instead of &/| -- not what the OP wants.Simson
@John-Machin Well there are two meanings: 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.