PEP 218 Re: ANN: set-0.1 module available

Bernhard Herzog bh at intevation.de
Tue May 21 05:07:35 EDT 2002


Gonçalo Rodrigues <op73418 at mail.telepac.pt> writes:

> >If an object is stored in a dict as a key, the only things that matter
> >are that
> >
> >1. its hash value doesn't change as long as the object is used as a key.
> 
> Doesn't this mean, in practice, that it is immutable?

Not necessarily. If the hash value can change if the state of the object
changes, you have to make sure that you don't change the object in such
a way as long as it's used as a key in a dict.

The easiest way to achieve this is of course to have the hash value
constant for the life-time of the object.

> To me, this requirement is just shifting responsabilities from one
> place to the other and not really solving the problem.

It may, yes. It's certainly not the best solution for objects in a set.

> >2. equal objects have equal hash values
> >
> >There may be some more subtle requirements. I'm not sure what happens
> >when two objects that have the same hash value but do not compare eqal
> >at first later become equal, for instance.
> 
> I believe 2. is more stringent:
> 
> equal objects iff equal hash values

That can't work. Hash values are ints which today means that it's a C
long and therefore either 32bit or 64 bit on most machines. Obviously
there are far fewer possible hash values than strings for instance, so
there must be at least two strings which are unequal but have the same
hash value.

An easy example for hashes of ints:

Python 2.2 (#1, Jan 17 2002, 21:04:07) 
[GCC 2.95.4 20011006 (Debian prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> -1 == -2
0
>>> hash(-1) == hash(-2)
1
>>> 

Most of the time, i == hash(i) for any python int except -1, because -1
is indicates an error in the C-level equivalent of __hash__.

   Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
MapIt!                                           http://www.mapit.de/



More information about the Python-list mailing list