Why are tuples immutable?

Jp Calderone exarkun at divmod.com
Thu Dec 16 00:13:49 EST 2004



On Wed, 15 Dec 2004 23:38:04 -0500, Adam DePrince <adam at cognitcorp.com> wrote:
>On Wed, 2004-12-15 at 10:26, Jp Calderone wrote:
> > On Wed, 15 Dec 2004 14:18:21 GMT, Roel Schroeven <rschroev_nospam_ml at fastmail.fm> wrote:
> > >Antoon Pardon wrote:
> > > > Op 2004-12-15, Fredrik Lundh schreef <fredrik at pythonware.com>:
> > > >>sorry, but I don't understand your reply at all.  are you saying that dictionaries
> > > >>could support mutable keys (e.g lists) by making a copy of the key?  how would
> > > >>such a dictionary pick up changes to the original key object?  (I'm talking about
> > > >>the key stored in the dictionary, not the key you're using to look things up).
> > > > 
> > > > 
> > > > You want to mutate a key that is within a dictionary?
> > > 
> > > No, we don't want to mutate it; as far as I know, that is exactly the 
> > > reason why dictionaries don't support mutable keys.
> > 
> >   Dictionaries support mutable keys just find.  What they don't 
> > support is unhashable keys.  
> > 
> >   For some objects, this is an important distinction: lists are 
> > mutable but not hashable.
> > 
> >   For other objects, it is not: instances of user defined classes 
> > are mutable and hashable.  This is handy since the default hash is 
> > based on identity instead of the values of attributes.
> > 
> >   Mutating an object in a dictionary is completely reasonable.  What
> > is unreasonable is wanting to make a change that would change its
> > hash value.
> 
> And how exactly do you propose to mutate an object without changing its
> hash value?
> 
> [snip - argument predicated on incorrect definition of the word "same"]
> 

    It is often useful to treat two objects as "the same" if they are 
/the same/ object.  In other words, identity can be a useful hash value.  
The attributes or other values (as in the case of an int or list, where 
the object `is' the value instead of `has' the value) don't matter.  
Since no mutation you can make to an object will change its identity, 
when identity is used as a hash value, any mutation is safe with respect 
to dictionaries.

  Memos, caches, and registries often benefit from this (although since 
many Python objects aren't hashable, they sometimes need to skip 
__hash__ and manually use id() to compute a suitable hash value).

  Jp



More information about the Python-list mailing list