42

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

4 Answers 4

50

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

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

1 Comment

Noteably, PEP335 made a proposal and was eventually rejected.
3

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

Comments

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.

1 Comment

No, you can not. (Since and is a keyword in Python.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.