Why are tuples immutable?

Jp Calderone exarkun at divmod.com
Fri Dec 17 20:35:02 CET 2004


On Fri, 17 Dec 2004 11:21:25 -0800, Jeff Shannon <jeff at ccvcorp.com> wrote:
> 
> No -- the mathematical definition of 'hashable' fails for mutable types, 
> and Python doesn't try to pretend that it can hash mutable types.  
> Python also provides features so that user-defined immutable types can 
> be hashed properly, and those features can be abused to pretend to hash 
> user-defined mutable types,  but that's not the same as saying that 
> Python is happy with mutable dictionary keys.  (One can abuse __add__() 
> to do all sorts of things other addition, too, but it would still be a 
> stretch to say that Python supports using + to do multiplication, it 
> just doesn't provide it on standard numeric types.)

  If I understand you correctly, you are overlooking (either by design 
or accident) this behavior:

    >>> class Foo:
    ...     pass
    ... 
    >>> f = Foo()
    >>> d = {}
    >>> d[f] = 'bar'
    >>> d
    {<__main__.Foo instance at 0xb7e5e60c>: 'bar'}

  Instances of the Foo class are quite mutable and hashable despite 
the complete absence of code in the class definition to make it so.
Nor is this behavior restricted to classic classes: make Foo's base
class object and the behavior remains the same.

  The correct characterization is that Python makes user-defined
mutable classes hashable (arguably correctly so) as the default
behavior.

  Jp



More information about the Python-list mailing list