Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is operator module missing `and` and `or`?

operator module makes it easy to avoid unnecessary functions and lambdas in situations like this:

import operator

def mytest(op, list1, list2):
    ok = [op(i1, i2) for i1, i2 in zip(list1, list2)]
    return all(ok)

mytest(operator.eq, [1, 2, 3], [1, 2, 3])         # True
mytest(operator.add, [-1, 2, -3], [1, -2, 33])    # False

Well, now I need to do i1 and i2, but to my surprise, I can't find and in the operator module! And the same applies to or! I know, and is not exactly operator, it's a keyword, but not, along with is and even del, are all keywords and all are included.

So what's the story? Why are they missing?

like image 212
Alois Mahdal Avatar asked Feb 27 '26 20:02

Alois Mahdal


2 Answers

Because you cannot convert boolean operators into python functions. Functions always evaluate their arguments, and boolean operators do not. Adding and and or to the operators module would also require adding a special kind of functions (like lisp "macros") that evaluate their arguments on demand. Obviously, this is not something python designers ever wanted. Consider:

if obj is not None and obj.is_valid():
    ....

you cannot write this in a functional form. An attempt like

  if operator.xyz(obj is not None, obj.is_valid()) 

will fail if obj is actually None.

like image 153
georg Avatar answered Mar 01 '26 10:03

georg


You can write these yourself, but you'll need to pass a function (e.g. lambda) for the second argument to prevent it from being evaluated at call time, assuming that the usual short-circuiting behavior is important to you.

def func_or(val1, fval2):
    return val1 or fval2()

def func_and(val1, fval2):
    return val1 and fval2()

Usage:

func_or(False, lambda: True)
func_and(True, lambda: False)
like image 40
kindall Avatar answered Mar 01 '26 11:03

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!