[Python-Dev] Getting values stored inside sets (original) (raw)

R. David Murray rdmurray at bitdance.com
Fri Apr 3 19:33:39 CEST 2009


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



More information about the Python-Dev mailing list