7

I was under the impression it was possible to overload and in Python, but reading through the docs just now, I realized that __and__ refers to the bitwise & operator, not logical and.

Am I overlooking something, or is it not possible to overload logical and in Python?

3
  • I'm curious: what would you like to make an overloaded and do? Or are you just asking for purely theoretical reasons? Commented Aug 31, 2015 at 12:53
  • Purely theoretical. I'm writing something that needs to work with Python AST. For most things like Add, I replace it with a call to __add__, but I was surprised that I couldn't find a function to replace an And node in AST with. Commented Aug 31, 2015 at 12:59
  • I don’t see a good reason why you would want to introduce custom behavior for logical operators that does not match the behavior from evaluating __bool__. Commented Aug 31, 2015 at 13:03

3 Answers 3

12

No this is not possible. There is a proposal that adds this functionality but for now, it is rejected.

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

Comments

2

No, it is not possible. See here.

2 Comments

Hm. is makes some sense to me, but I'm surprised that and and or cannot be overloaded.
Yes, it is indeed a limitation of the language. But you can override the bitwise operators & and | , as you noticed. This is used by e.g. SQLAlchemy and you can also use it yourself of course.
2

There is no straight way to do this. You could override __nonzero__ for your objects to modify their truth value.

class Truth: def __init__(self, truth): self.truth = truth def __nonzero__(self): return self.truth t = Truth(True) f = Truth(False) print bool(t and t) print bool(t and f) print bool(f and f) 

1 Comment

Compatibility tip: __nonzero__ has been renamed to __bool__ in 3.X.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.