Help understanding the decisions *behind* python? - immutable objects

Dave Angel davea at
Mon Jul 27 22:14:14 CEST 2009

Benjamin Kaplan wrote:
> On Sun, Jul 26, 2009 at 2:24 PM, John Nagle<nagle at> wrote:
>> Beni Cherniavsky wrote:
>>> On Jul 22, 9:36 am, Hendrik van Rooyen <hend... at>
>>> wrote:
>>>> On Tuesday 21 July 2009 15:49:59 Inky 788 wrote:
>>>> <snip>
>>> problem.
>>    An interesting issue is Python objects, which are always mutable.
>> A "dict" of Python objects is allowed, but doesn't consider
>> the contents of the objects, just their identity (address). Only
>> built-in types are immutable; one cannot create a class of immutable
>> objects.
>> So things like "frozenset" had to be built into the language.
>> A tuple is really a frozen list.  Arguably, frozen objects
>> should have been a general concept.  Conceptually, they're
>> simple - once "__init__" has run, there can be no more changes
>> to fields of the object.
>>    Compare the C++ approach, where you can have a "map" of
>> any object that defines the "<" operator.  Python has
>> "__cmp__" for objects, but built-in dictionaries don't use it.
>> Of course, one could create a "map" class in Python that
>> uses "__cmp__", which would allow dictionary-type operations
>> on arbitrary objects.
> Python dictionaries are hash maps so they use hashes, not comparisons,
> to store objects. By default the hash is equal to the object's
> identity but all you need to do to change it is define your own
> __hash__ method. If you were to make a C++ hash map, it wouldn't use
> comparisons either.
> <snip>
I think you'll find that to make a proper dict of user-objects, you need 
to define not only __hash__(), but also __eq__() methods.   A hash is 
only a starting place.  In case of collision, the dict class calls 
another method to make sure.

And of course, for the dict to function reasonably, you have to make 
sure that the hash and eq functions return consistent results, at least 
pretending that the objects involved are immutable.


More information about the Python-list mailing list