Re: Why don't stringobjects have methods?

Consultant (amrit@xvt.com)
Fri, 1 Apr 1994 09:22:28 -0700 (MST)

> The interesting question is _why_ strings and tuples (etc) are immutable,
> and I don't have an interesting answer to that. Maybe Guido will shed
> more light on these decisions?
>
I don't know why string & tuples are immutable, but I have a guess.
Since all assignments in Python merely break the binding of the target
then creates a (possibly) multiple reference to the new object,
if strings were mutable, then there would be some very strang behavior
for strings:

> s = t = 'hello'
> s[0] = 'j'
>
> print t
'jello'

Now this behavior already works this way for lists, but users are more used
to this behavior for large, cumbersome datatypes. (C for example works this
way for arrays, and Icon lists work this way.)

Now, having this behavior for strings is definitely not the norm, so making
strings immutable objects prevents this from occuring. There may be as
many references to a string object as you like, but there will never be the
kind of side-effects decribed above.

> s = t = 'hello'
> s = 'j' + s[1:]
> print s, t
'jello' 'hello'

In this case, a new string is created and bound to 's', so there are no nasty
side effects.

This behavior actually opens the door for some optimizations in Python.
A few months ago, I wanted to simulate LISP style symbols: the idea is that
a symbol is like a string but comparison for equal is done in constant time
because a symbol is really a pointer. You can do this in Python simply
by using constants for frequently used string vaules:

A = 'a'
B = 'b'
C = 'c'

x = A

...

if x is A:
process_a()

elif x is not C:
process_c()

The key here is that we wonly assign a symbol one of those other constants
(A, B, C). Then we can do comparisons using "is" and "is not" instead of a
more expensive ==, != comparison. This is only possible due to the reference
sharing nature of strings.