39

I tried overriding __and__, but that is for the & operator, not and - the one that I want. Can I override and?

airportyh
  • 20,858
  • 13
  • 55
  • 71

4 Answers4

47

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).

Rick supports Monica
  • 38,813
  • 14
  • 65
  • 113
dF.
  • 71,061
  • 29
  • 127
  • 135
  • 2
    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. – DRayX Apr 03 '17 at 16:52
  • @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. – kdb Mar 07 '21 at 09:18
37

You cannot override the and, or, and not boolean operators.

Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
  • 15
    Noteably, [PEP335](https://www.python.org/dev/peps/pep-0335/) made a proposal and was eventually rejected. – jpmc26 May 19 '17 at 02:09
3

Not really. There's no special method name for the short-circuit logic operators.

S.Lott
  • 373,146
  • 78
  • 498
  • 766
1

Although you can't overload __and__ you can use infix to overload and. You would use &and& to represent the and operator in this case.