Class Variable Access and Assignment

Christopher Subich csubich.spam.block at spam.subich.block.com
Mon Nov 7 14:03:45 EST 2005


Antoon Pardon wrote:
> Op 2005-11-04, Christopher Subich schreef <csubich.spam.block at spam.subich.block.com>:
>>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. 

Problem:
"""
class B:
    x = 1
classx = b()
instx = b()
instx.x = 5

def addtox(o):
    o.x += 1

addtox(instx)
print B.x # 1
print instx.x # 6; we both agree on this one
addtox(classx) # You argue this should AttributeError
print B.x # ?! -- 1 currently, you argue 2 if no error
print class.x # we both agree 2, if no error
"""

a.x is /not/ a namespace issue at all; it's an attribute issue.

.x is not a name, it is an attribute.  Python namespaces are lexically 
scoped, not dynamically scoped; if, as you argue, .x should be a name in 
a namespace, then you argue above that addtox in the above should work 
on instx but fail on classx.  But this /cannot be determined at compile 
time/, because the attribute space is attached to the object passed in 
as the parameter.

I repeat: this is not a name issue at all, it is an attribute issue. 
Python's behaviour is counterintuitive from some angles, but it is the 
only behaviour that is consistent with attributes in general, given the 
signature of __iadd__ as-is.

> 
> 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.

There are no name spaces.

> 
> 
> 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.

Immutable? I do not think that word means what you think it means.



More information about the Python-list mailing list