Why are tuples immutable?

Jeff Shannon jeff at ccvcorp.com
Fri Dec 17 20:37:36 EST 2004


Jp Calderone wrote:

>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'}
>  
>

You're right, I *was* overlooking that behavior, and it was by accident.

>  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.
>  
>

Okay, so it appears that for user-defined classes, there is (effectively 
if not in fact) a default __hash__() which simply returns the object id, 
but list explicitly defines __hash__() to throw a TypeError.

That does put a kink in my argument that Python is simply refusing to 
guess in the face of ambiguity.  I'm still convinced that disallowing 
lists as dict keys is a good thing, but it leaves me unable to explain 
why __hash__()-less user-defined classes (which are mutable almost by 
definition) are allowed.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list