Mutable class attributes are shared among all instances, is it normal ?

Donn Cave donn at drizzle.com
Fri Jun 8 00:48:16 EDT 2001


Quoth Chris Barker <chrishbarker at home.net>:
| Alain TESIO wrote:
|> 
|> Hi, sometimes class attributes added just after
|> "class ...:" outside a functions interfere among
|> instances, more precisely mutable objects are
|> linked to the same object as if it were a static
|> attribute.
|> 
|> See the test case below.
|> 
|> If I delete the line "val=[None]" in class
|> Y and add "self.val=[None]" in its __init__
|> it works as class X.
|> 
|> Is it a bug or did I miss something ?

[... snipping some explanation ...]
| Now, the reason you have your confusion is that since everything in
| Python is a reference, the distiction that matters is whether it is
| mutable or not. A mutable object (a list) can be changed in place. An
| immutable object can not. If you assign a new value to a name that
| references an object, the name then gets assigned to your new object,
| and the old one is de-refereced (it will be garbage collected if there
| is nothing else pointing to it. Whe you alter a mutable object, however
| (list[index] = something) you have not changed the reference, but you
| have changed the object it is pointing to.

I have no argument with the facts here, but I have to disagree about
the reason for the confusion.

It should be clear from this that the distinction between mutable
and immutable objects here is actually completely irrelevant, and
when we introduce this red herring into the picture we make a simple
matter much harder to understand.  (It's so often repeated here, yet
makes no sense to me.  I don't wish to pick on this post, the author
went went to considerable trouble to help out and I'm just off on a
rant about this detail, because the subject has the word "mutable".)

When I write "self.x = a", it does not matter in any way whether
self.x is mutable.  It is purely irrelevant.

To understand why "self.x = a", we really have to understand the
Python object/reference/namespace model, which again has nothing
to do with mutability.  If you understand what "self.x = a" means
in that model ("make name 'x' in namespace 'self' refer to the
same object as name 'a' in the default namespace[s], possibly
hiding another name in a posterior namespace" ... uh, there has
to be a better way to say that!) then you will not be confused.
If you understand it different (i.e., wrong) you will be confused
all the time.

Now I think what people mean to point out here, is that given the
realities of life with Python, one may choose to substitute
"self.x = a" with some expression that modifies a mutable object,
like "self.x[0] = a".  That's fine, but of course the point is
not that self.x is mutable, the point is that you are modifying it.

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list