Scope rule pecularities

Antoon Pardon apardon at forel.vub.ac.be
Thu May 6 10:54:47 EDT 2004


Op 2004-05-06, Yermat schreef <loic at fejoz.net>:
> Antoon Pardon wrote:
>> [...]
>>   a1 = Int(14)
>>   a2 = Int(15)
>>   b = Int(23)
>>   
>>   print a1, a2 
>>   
>>   def foo():
>>   
>>     a1 += b 
>>     a2.__iadd__(b)
>>     
>>   foo()
>>   
>>   print a1, a2
>> 
>> 
>> Now the a1 += b line doesn't work, it produces the following error:
>> 
>>   UnboundLocalError: local variable 'a1' referenced before assignment.
>> 
>> The a2.__iadd__(b) line however works without trouble.
>> 
>> 
>> Now I think I understand what is causing this, but I think this
>> kind of thing shouldn't happen. If a += b is just syntatic sugar
>> for a.__iadd__(b) then the first should be acceptable where the
>> second is acceptable.
>> 
>
> Here we are again !
> Do you mind to try :
>
> def foo():
>      global a1, a2
>      a1 += b
>      a2.__iadd__(b)
>
> Note also that the second line were not executed so you can't know if it 
> were working...

I know it worked because I commented out the first and tried again.

Beside you missed the point. I don't need solutions, I know the
work arounds to make it work. The point is that although a += b
is supposed to be syntactic sugar for a.__iadd__(b), you need
a global (and even that won't help if you have nested functions
and the a is on an intermediate level) to make the first work
but not for the second.

-- 
Antoon Pardon



More information about the Python-list mailing list