can a class instance ever be hashable?

Rainer Deyke root at rainerdeyke.com
Fri Sep 22 05:26:59 CEST 2000


"Aahz Maruch" <aahz at panix.com> wrote in message
news:8qee1s$kfj$1 at panix3.panix.com...
> The basic question is whether the attributes that make up the hash can be
> changed by the class user after the instance is created.  If the answer
> is "yes", then the class is mutable and you can't hash it.  If you're
> familiar with SQL DBs, the hash is fundamentally equivalent to a primary
> key -- you can change the non-key values once you create a record, but
> you're not allowed to change the primary key.  (Yes, I know this isn't a
> strictly correct analogy, but it gets the point across, I think.)

Then there are different levels of immutability:

1. Immutable primitives (strings, tuples, etc.) that absolutely cannot be
changed.

2. Class instances that do not change by design (although it is always
technically possible to modify them).

3. Class instances that by design do not change their hash value.  This
would include any instances that are hashed by id.

I normally don't think of category 3 as immutable.

There are also four possibilities regarding __cmp__ and __hash__:

1. Neither is defined, so both use id by default.  This is appropriate for
most classes, and may be safely hashed.  No two instances of the class
compare equal, and ordering is arbitrary but deterministic.

2. __cmp__ is defined, but __hash__ isn't.  Objects of such a class are not
hashable.

3. __hash__ is defined but __cmp__ isn't.  This is possible, but serves no
purpose.  The object should not change its hash value while it is in any
dictionary or similar hash-based data structure.

4. Both __cmp__ and __hash__ exist.  Again, the object should not change its
hash value while it is in any dictionary or similar hash-based data
structure.  Another requirement is that objects which compare equal have
identical hash values.  In rare circumstances, it might make sense to remove
the object from a dictionary, modify it in a way that changes its hash
value, and reinsert it.


--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor




More information about the Python-list mailing list