[Tutor] Tuples, Dictionarys and mutable vs. immutable

D-Man dsh8290@rit.edu
Mon, 26 Feb 2001 13:59:58 -0500

On Sun, Feb 25, 2001 at 08:30:59PM -0800, Sheila King wrote:
| OK, now I'm really confused.
| I don't really "get" the difference yet, between mutable and immutable types,
| but I figured I would eventually get it. But at least I thought I understood
| that an object could not change its type or its id. At least I thought I
| understood that.

Since you understand C++ I'll make an analogy with it.

In Python all identifiers are "typeless" pointers (void*).  They refer
to an object, which has a particular type, when you assign that object
to them.  If you assign a different type to it, it will refer to a
different type of object.  

Mutable objects are objects that you can actually change.  It is as if
they have all public data members, or provide public mutator
functions.  Immutable objects don't have any public data that can be
changed (only read/copied) and no public mutator methods.

The *identifiers* are always mutable (since they are little more than
pointers) -- you can assign a new object of whatever type you want to
it whenever you want to.

It is useful, IMO, to name your identifiers to describe the type of
object you expect it is referring to.  This helps readability.
However, if need be, python allows you to assign a different type of
object to it.  This is coolest when debugging since you can simply
throw some new code in the middle to see what the state of the system
is at that time without the overhead of static type checking (or C's
requirement that all identifiers be declared at the beginning of a

Also, as others have already mentioned, id() simply returns the
address of the object its argument refers to.  CPython has a tendency
to free() objects shortly after the last reference is removed, and
then to malloc() the next new object at that same location.  (Although
I'm not sure if it actually calls malloc/free or just maintains it's
own free lists)  This is why it seems you are seeing multiple objects
with the same id.  They had the same id, just not simultaneously.

BTW,  In the interactive interpreter, all expressions get assigned to
a variable named _.  Ex :

>>> class Foo :
...     def __del__( self ) :
...             print "I was del'ed : %d" % id( self )
>>> obj = Foo()
>>> id( obj )
>>> obj = None
I was del'ed : 8171332
>>> Foo()
<__main__.Foo instance at 007CF46C>

# note : I didn't assign the new object to anything, but it wasn't
# del'ed yet
# this is because it was assigned to _, so a reference still exists

>>> print _
<__main__.Foo instance at 007CF46C>
>>> 13
I was del'ed : 8189036

# here I implicitly assigned 13 to _, so the Foo object was del'd


This peculiarity exists only in the interactive interpreter.  I
believe it is so that you can maintain a handle to a return value or
expression after the fact, if you didn't realize you wanted it  when
you typed the expression.