why are some types immutable?

"Martin v. Löwis" martin at v.loewis.de
Sun Jan 16 06:40:45 EST 2005


Torsten Mohr wrote:
> reading the documentation (and also from a hint from this NG)
> i know now that there are some types that are not mutable.
> 
> But why is it this way?

There are various reasons, some apply for some types, and
some for others:
- immutable objects are hashable - their hash value will not
   change during their life time (if it is a container, the
   contained objects also need to be hashable). Mutable
   types are typically not hashable.
   A type needs to be hashable to act as a dictionary key.
- immutable objects can be shared, allowing the same
   reference to be used in multiple places. For mutable
   objects, one often needs to make a copy of the object
   before storing it.
- immutable types can often be implemented more efficiently.
   For examples, the length of a tuple is fixed, as tuples
   are immutable. Therefore, memory management for tuples
   is simpler (they only require one memory block, instead
   of two, as lists do).
- for some types, the expectation of immutability is so
   common that people would complain massively if they were
   mutable. This, in particular, applies to numbers - people
   expect that after
   x = 7
   the variable x keeps the value, and that the "7" object
   cannot suddenly change its value to 8.

> From an overhead point of view i think it is not optimal,
> for example for a large string it could be much faster to
> have it changed in place, not generating a new one for
> every step in a change.

For strings, the following points apply; as a net result,
the overhead is *less* than it would be if strings were
mutable:
- strings must be hashable, so they can be used as
   a dictionary key. If you would modify, say,
   len.func_name, then newly imported code could not
   find the len function anymore.
   It would be possible to solve this by introducing
   an additional immutable identifier type, but then
   you would need to create copies of strings (to
   create identifier object). Many applications might
   break which currently use strings as dictionary
   keys.
- strings are currently assumed to be shareable.
   You pass strings to functions which then store
   the strings in global variables, object attributes,
   etc. In all these places, copies would need to be
   made if strings were mutable, since the caller
   might chose to modify the string afterwards.
- immutable strings consume less memory than
   mutable strings would, because a string is made
   up of just one memory block.

Regards,
Martin



More information about the Python-list mailing list