For instance, these are defined in the operator module and can be used as such:
import operator
print operator.__add__ # alias add -> +
print operator.__sub__ # alias sub -> -
print operator.__and__ # alias and_ -> &
print operator.__or__ # alias or_ -> |
Then what is the equivalent of and and or?
print operator."and ?????" # should be boolean-and
print operator."or ????" # should be boolean-or
These do not exist. The best you can do is to replace them with a lambda:
The reason is you can not implement the complete behavior of
andororbecause they can short circuit.E.G:
If
variableisTrue, thelong_fonction_to_executewill never be called because Python knows thanorhas to returnTrueanyway. It’s an optimization. It’s a very desirable feature most of the time, as it can save a lot of useless processing.But it means you cannot make it a function:
E.G:
In that case,
long_fonction_to_executeis called even before being evaluated.Luckily, you rarely need something like that given the fact that you an use generators and list comprehensions.