Class Variable Access and Assignment

Antoon Pardon apardon at
Mon Nov 7 09:04:04 CET 2005

Op 2005-11-04, Christopher Subich schreef <csubich.spam.block at>:
> Antoon Pardon wrote:
>> Except when your default is a list
>> class foo:
>>   x = [] # default
>> a = foo()
>> a.x += [3]
>> b = foo()
>> b.x
>> This results in [3]. So in this case using a class variable x to
>> provide a default empty list doesn't work out in combination
>> with augmented operators.
> This has nothing to do with namespacing at all,

Yes it has.

> it's the Python 
> idiosyncracy about operations on mutable types.  In this case, += 
> mutates an object, while + returns a new one -- as by definition, for 
> mutables.

It is the combination of the two.

If python had chosen for an approach like function namespaces, the
problem wouldn't have occured either. What would have happened then
is that the compilor would have noticed the a.x on the right hand
side and based on that fact would then have deciced that all a.x
references should be instance reference (at least in that function
block). The a.x += ... would then result in an AttributeError being raised. 

You may prefer the current behaviour over this, but that is not the
point. The point is that resolution of name spaces does play its
role in this problem.

It also has little to do with mutable vs immutable types.
Someone could implement an immutable type, but take advantage
of some implemtation details to change the value inplace
in the __iadd__ method. Such an immutable type would show
the same problems.

Antoon Pardon

More information about the Python-list mailing list