[Python-Dev] bool does not want to be subclassed?

Phillip J. Eby pje at telecommunity.com
Mon Feb 16 15:38:10 EST 2004


At 03:15 PM 2/16/04 -0500, François Pinard wrote:

>So, instead of explaining how we should cleverly use `__hash__' to
>describe immutability, we might describe what `__hash__' ought to
>be, and then merely notice that hashable objects could be useful to
>represent immutable objects (whether user objects or builtin objects).

Actually, it might be even better to start with equality.  Hashing is only 
meaningful for objects that can be tested for equality.  That is:

* By default, objects are equal only to themselves.  But you can change 
this by overriding __cmp__ or __eq__.

* Hashing is a technique used to group objects according to possible 
equality.  So, if you want to create a hashable object that can be "equal 
to" other objects, it must return the same hash value as the objects it 
compares equal to.

* Hash values must remain constant over the lifetime of an object.  Thus, 
if an object may compare equal to a different set of objects over its 
lifetime, it must *not* be hashable.

* Therefore, if an object is to be hashable, any attributes of the object 
that are used in calculating the hash (or performing comparisons) may not 
be changed once the its __hash__ method has been called.  Usually, this is 
implemented by making an object completely unchangeable once created (e.g. 
tuples), but some user classes may implement this by "freezing" an object's 
contents once it is hashed (e.g. kjbuckets.kjSet).




More information about the Python-Dev mailing list