[Python-Dev] Why should the default hash(x) == id(x)?
Noam Raphael
noamraph at gmail.com
Wed Nov 2 02:21:38 CET 2005
Hello,
While writing my PEP about unifying mutable and immutable, I came upon this:
Is there a reason why the default __hash__ method returns the id of the objects?
It is consistent with the default __eq__ behaviour, which is the same
as "is", but:
1. It can easily become inconsistent, if someone implements __eq__ and
doesn't implement __hash__.
2. It is confusing: even if someone doesn't implement __eq__, he may
see that it is suitable as a key to a dict, and expect it to be found
by other objects with the same "value".
3. If someone does want to associate values with objects, he can
explicitly use id:
dct[id(x)] = 3. This seems to better explain what he wants.
Now, I just thought of a possible answer: "because he wants to store
in his dict both normal objects and objects of his user-defined type,
which turn out to be not equal to any other object."
This leads me to another question: why should the default __eq__
method be the same as "is"? If someone wants to check if two objects
are the same object, that's what the "is" operator is for. Why not
make the default __eq__ really compare the objects, that is, their
dicts and their slot-members?
I would be happy to get answers.
Noam
More information about the Python-Dev
mailing list