I tried overriding __and__, but that is for the & operator, not and - the one that I want. Can I override and?
4 Answers
No you can't override and and or. With the behavior that these have in Python (i.e. short-circuiting) they are more like control flow tools than operators and overriding them would be more like overriding if than + or -.
You can influence the truth value of your objects (i.e. whether they evaluate as true or false) by overriding __nonzero__ (or __bool__ in Python 3).
2 Comments
DRayX
The control flow (lazy evaluation of the right hand side) semantics could still be maintained by having the overload be a binary operator where right hand side is passed as a callable instead of as a value.
kdb
@DRayX Not even that is necessary. The short-circuit part could simply be preserved as part of the operator, and the hypothetical
__and2__ function would only be called, if the first argument evaluates to a truthy value. a and b would be equivalent to a.__and2__(b) if a else a then. Not as regular as other operator functions, but that choice would enforce retaining short circuiting and provide better performance.