On Fri, 3 Apr 2009 at 17:57, Paul Moore wrote:
In fact, Python seems to be doing something I don't understand:

class Element(object):
...    def __init__(self, key, id):
...        self.key = key
...        self.id = id
...    def __eq__(self, other):
...        print "Calling __eq__ for %s" % self.id
...        return self.key == other
...    def __hash__(self):
...        return hash(self.key)
...
a = Element('k', 'a')
b = Element('k', 'b')
a == b
Calling __eq__ for a
Calling __eq__ for b
True
a == a
Calling __eq__ for a
Calling __eq__ for a
True


Why does __eq__ get called twice in these cases? Why does a == b, as
that means a.key == b, and clearly a.key ('k') does *not* equal b. Or
are there some further options being tried, in str,__eq__ or
object.__eq__? The documentation doesn't say so... Specifically,
there's nothing saying that a "reversed" version is tried.

a == b

So, python calls a.__eq__(b)

Now, that function does:

a.key == b

Since b is an object with an __eq__ method, python calls
b.__eq__(a.key).

That function does:

a.key == b.key

ie: the OP's code is inefficient :)

--David
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to