Hash of class from instance

Mick Krippendorf mad.mick at gmx.de
Wed Feb 2 13:15:23 EST 2005


Joakim Storck wrote:
> [...] the hash values of classes will be used as
> keys in a dictionary that serve as an object pool. [...]

That does seem unwise (as Teal'c would have uttered). The spec says:

----
      hash( object)

Return the hash value of the object (if it has one). Hash values are
integers. They are used to quickly compare dictionary keys during a
dictionary lookup. Numeric values that compare equal have the same hash
value (even if they are of different types, as is the case for 1 and
1.0).
----

Normally the following should hold (not mentioned in the above spec but
true for Java, e.g.): if a and b are objects such that a equals b then
hash(a) equals hash(b). This does not imply that if hash(a) equals
hash(b) also a equals b. More formally: (a == b) -> (hash(a) ==
hash(b)).

In Python there seems to be no guarantee that different objects also
have different hash values. So let's assume we have class objects Foo
and Bar, which by some unlikely incident happen to have the same hash
values, then storing them in a dictonary under their respective hash
values (which are identical) would most probably lead into a problem,
secifically the problem that you'd end up accessing Foo when you indeed
think you are accessing Bar, or vice versa. Just try this:

 >>> my_pseudo_hash_code = 1
 >>> my_dict = {my_pseudo_hash_code:"gnarf",
my_pseudo_hash_code:"snarf"}
 >>> print my_dict

Mick.




More information about the Python-list mailing list