rophl
rophl

Reputation: 187

Operator binding in Python

I have a containery object something like this:

class foo(object):
  def __init__(self,value):
    self.value = value
  def __eq__(self,other):
    return self.value == other

Which I can use like this:

>>> var = foo(4)
>>> var == 4
True
>>> var == 3
False
>>> # So far so good
>>> var == foo(4)
True
>>> var == foo(3)
False
>>> # Huh

My question is: what is happening that allows this to magically "just work"? How does Python bind the == operator inside __eq__ so that the value member of both sides is compared?

Upvotes: 2

Views: 407

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121972

If an __eq__ method returns NotImplemented for a given argument, Python will try the same test in reverse. So x == y will try x.__eq__(y) first, if that returns the NotImplemented singleton, y.__eq__(x) is tried.

This applies to the comparison inside your __eq__ method as well; you are essentially comparing:

self.value == other

which is:

4 == other

which is:

4.__eq__(other)

which returns NotImplemented:

>>> var = foo(4)
>>> (4).__eq__(var)
NotImplemented

So Python tries other.__eq__(4) instead, which returns True.

Upvotes: 6

Related Questions