0

I couldn't find the official glossary of python operators but at least it seems that operator library of python doesn't include and or or keyword. They do have operator.and_, but it's for bitwise and operator(&). What makes me more confused is that they do include is or not keywords as operators.

In short, isn't and(and or) an operator? If it isn't, what is the standard of being an operator in Python? I though I'm pretty familiar with python but this problem confuses me a lot at the moment.

  • `and` and `or` are operators, but they are not overridable in the way that some other operators are. – khelwood May 15 '18 at 13:36
  • See also https://stackoverflow.com/questions/471546/any-way-to-override-the-and-operator-in-python – Don May 15 '18 at 13:38

1 Answers1

3

Yes, it's an operator. But it's not like the other operators in the operator module.

and short-circuits (i.e., it evaluates its second argument only if necessary). or is similar. Therefore, neither can be written as a function, because arguments to functions are always fully evaluated before the function is called. In some cases this would make no real difference, but when the second argument contains a function call with side effects (such as I/O), or a lengthy calculation, and's behavior is very different from that of a function call.

You could implement it by passing at least the second argument as a function:

def logical_and(a, b):
    if not a:
       return a
    return b()

Then you could call it as follows:

logical_and(x, lambda: y)

But this is a rather unorthodox function call, and doesn't match the way the other operators work, so I'm not surprised the Python developers didn't include it.

kindall
  • 178,883
  • 35
  • 278
  • 309