> I don't have the Python source code with me, so I could be dead-wrong
> about this, but I suspect there may be some implementation reasons
> for making strings immutable. (Someone correct me if I'm wrong.)
> If you store strings in a hash table, you have to delete them, and
> rehash/re-store them, to change their value (so later occurrences hash
> to the new bucket).
Strings are not stored in a hash table. The implementation of all
Python objects (including strings) consist of a header plus data. For
mutable objects (lists, dictionaries) the data is pointed at by a
pointer in the header; for immutable objects (strings, tuples, numeric
types), the data is part of the structure of which the header is the
start. During the lifetime of an object the address of the header
does not change. (This header contains information such as the type
of the object and the reference count.)
Internally, references to objects only contain the pointer to the
header. Since the header's address does not change during the
object's lifetime, objects don't have to be chased when they are
Mutable strings could be implemented by creating objects that contain
a header with a pointer to the string. When the string object is
changed, the pointed-to string would need to be changed, but not the
location of the header.
Someone else in this thread already mentioned one reason why strings
are not mutable. (If you have s = t = 'hello', than saying s = 'j'
would cause unexpected results when you print t.) Guido may come up
with other good reasons for not allowing mutable strings. My guess is
that he just doesn't like them.
Sjoerd Mullender, CWI, P.O. Box 94079, 1090 GB Amsterdam, The Netherlands
E-Mail: Sjoerd.Mullender@cwi.nl; Phone: +31 20 592 4127; Fax: +31 20 592 4199