Death to tuples!

Mike Meyer mwm at mired.org
Mon Nov 28 16:44:44 EST 2005


skip at pobox.com writes:
>     Mike> Tuples have the problem that they are immutable, except when
>     Mike> they're not (or for proper values of immutable, your
>     Mike> choice). They're hashable, except when they're not. Or
>     Mike> equivalently, they can be used as dictionary keys - or set
>     Mike> elements - except when they can't.
> For those of us not following this thread closely, can you identify cases
> where tuples are mutable, not hashable or can't be used as dictionary keys?
> I've never encountered any such cases.

Actually, that didn't come from this thread. But it happens if one of
the elements in the tuple is mutable. For instance:

>>> t = [],
>>> type(t)
<type 'tuple'>
>>> t == [],
True
>>> hash(t)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: list objects are unhashable
>>> t[0].append(1)
>>> t == [],
False
>>> {t: 23}
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: list objects are unhashable
>>> 

For builtins, the three cases - hashable, immutable and usable as
dictionary keys - are all identical. Instances of Python classes with
proper __hash__ and __eq__ defintions will be hashable and usable as
dictionary keys. Immutable for them is a messy question.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list