Why are tuples immutable?

Antoon Pardon apardon at forel.vub.ac.be
Tue Dec 21 10:47:10 CET 2004


Op 2004-12-18, Nick Coghlan schreef <ncoghlan at iinet.net.au>:
> Antoon Pardon wrote:
>> Would you have us construct two related classes each time we find
>> ourselves in such a situation and copy an object from one
>> class to the other depending on the circumstances?
>
> Python itself seems to think so, given the pairings of set/frozenset & list/tuple.
>
> Using genuinely immutable objects as dictionary keys is much easier than saying 
> "while this object is part of a dictionary, don't alter it's hash value or 
> comparison results". Instead, the immutable version is provided to say 
> "alterations are not allowed on this copy"

Why then doesn't python think the same about sorted lists. When I have a
sorted list and do operations on it that depend on it being sorted,
I can mess things up just as easily by mutating an element in that
sorted list as I can mess things up by mutating a dictionary key.


> You can certainly *do* the former (using __hash__ and appropriate comparison 
> overrides), but it isn't particularly easy to do correctly,

> and hence usually 
> isn't a great idea unless copies are *really* expensive (and even then, a 
> shallow copy approach can often suffice).

The problem is you have to make copies evrywhere. You have to copy when
you insert a key, you have to make a copy when you access by key, you
have to copy when you want your key be used as an object.

-- 
Antoon Pardon



More information about the Python-list mailing list