Why doesn’t the operator module have a function for logical or?

Posted on

Question :

Why doesn’t the operator module have a function for logical or?

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

Asked By: max


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.

Answered By: max

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)
Answered By: Petr Viktorin

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:

Answered By: phihag

Leave a Reply

Your email address will not be published. Required fields are marked *