[Tutor] What does Python gain by having immutable types?

Orri Ganel singingxduck at gmail.com
Tue Nov 15 04:11:48 CET 2005


Hugo González Monteverde wrote:

>>Quite often the only answer is "just because". Some features are
>>the way they are because that's Guido's pesonal preference. Others
>>may disagree with him but it's his language and he gets to pick
>>what he thinks is best - the benign dictator syndrome.
>>    
>>
>
>There's also the issue that immutability is Python's way of dealing with 
>  "passing by value" and "passing by reference".  And that removing the 
>difference between mutable and immutable objects would mutate (no pun 
>intended) the language in a big way.
>
>Hugo
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
I've also heard the argument that, in the case where you want to be able 
to hash a sequence, you need an immutable sequence type.  Otherwise, 
when you do something like:

 >>> dicta = {}
 >>> tupb = (1,2)
 >>> tupc = (1,2)
 >>> dicta[tupb] = "34"
 >>> tupb.append(3) # raises an AttributeError b/c tuples are immutable 
and don't have append functions
 >>> dicta[tupb] = "45"

Would you expect dicta[tupb] to produce "34" or "45"?  And what of 
dicta[tupc]?  I believe this issue is one of whether to hash by identity 
or content.  When hashing, the implied promise is that all objects whose 
contents are the same should produce the same value, but one also 
expects one key to map to one value.  Without immutable types, where the 
identity and the content are intertwined, you get counterintuitive 
behavior a la the above mini-example (in reality, when you put two 
immutable objects with the same content in a dictionary, they both map 
to the same value - the last one assigned).  I'm sure someone more 
knowledgeable will come along and shed the bright light of understanding 
where my feeble candle flickers, but till then, HTH.

-Orri

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.



More information about the Tutor mailing list