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?

ArtOfWarfare
  • 20,617
  • 19
  • 137
  • 193
  • I'm curious: what would you like to make an overloaded `and` do? Or are you just asking for purely theoretical reasons? – PM 2Ring Aug 31 '15 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. – ArtOfWarfare Aug 31 '15 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__`. – poke Aug 31 '15 at 13:03

3 Answers3

12

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

Salailah
  • 435
  • 7
  • 12
2

No, it is not possible. See here.

Community
  • 1
  • 1
rkrzr
  • 1,842
  • 20
  • 31
  • Hm. `is` makes some sense to me, but I'm surprised that `and` and `or` cannot be overloaded. – ArtOfWarfare Aug 31 '15 at 12:49
  • 1
    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. – rkrzr Aug 31 '15 at 12:52
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)
  • 2
    Compatibility tip: `__nonzero__` has been renamed to [`__bool__`](https://docs.python.org/3.5/reference/datamodel.html?highlight=nonzero#object.__bool__) in 3.X. – Kevin Aug 31 '15 at 13:03