Modules are hashable?!

Alex Martelli aleaxit at yahoo.com
Fri Sep 3 10:26:31 CEST 2004


Jason Lai <jmlai at uci.edu> wrote:

> Maurice LING wrote:
> > 
> > The idea that I get from reading this thread is that objects that can be
> > type compared (comparing the contents) are not hashable, and they are
> > list, strings, tuples and dictionary. Is there any others that fall into
> > this category? Is there any way to make them hashable?
> 
> Well, strings and tuples are immutable, so they provide a hash function
> (since it's safe to hash them by contents; the contents are pointers 
> that don't change.) Anything that provides a hash function can be 

Yes, a tuple's "pointers" don't change, but they may refer to objects
that do, and in this case the tuple need not be hashable.  E.g.:

>>> a=tuple([ {} ])
>>> hash(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: dict objects are unhashable

Since the tuple has (as its only item) a dict, the tuple itself isn't
hashable -- the error message indicates the type of the item that fails
to be hashable.

> hashed. You could theoretically create a new list type that works 
> exactly like a normal list, but hashes based on ID.

No, if a==b and hash(a)!=hash(b) all hell would break loose.  Don't go
there.


Alex



More information about the Python-list mailing list