40

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

airportyh
  • 21,948
  • 13
  • 58
  • 72

4 Answers4

48

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
  • 43,029
  • 15
  • 76
  • 119
dF.
  • 74,139
  • 30
  • 130
  • 136
  • 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
40

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 16
    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
  • 384,516
  • 81
  • 508
  • 779
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.