Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 827
max Avatar asked Oct 25 '11 19:10

max


People also ask

Does Python have logical operators?

Python has three logical operators: and , or , and not .

What does Operator module do in Python?

The Python operator module is one of the inbuilt modules in Python, and it provides us with a lot of functions such as add(x, y), floordiv(x, y) etc., which we can use to perform various mathematical, relational, logical and bitwise operations on two input numbers.

What are the three types of logical operators in Python?

There are mainly three types of logical operators in python : logical AND, logical OR and logical NOT.


2 Answers

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.

like image 184
Petr Viktorin Avatar answered Nov 15 '22 15:11

Petr Viktorin


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)
like image 33
phihag Avatar answered Nov 15 '22 14:11

phihag