Scope rule pecularities

Holger Türk holger.tuerk at gmx.de
Thu May 6 11:17:31 EDT 2004


Hello Antoon,

Antoon Pardon wrote:
> Well to test things out I wrote the following:
> 
> 
>   class Int:
>   
>     def __init__(self, v):
>       self.value = v
>   
>     def __add__(self, term):
>       return Int(self.value + term.value)
>   
>     def __iadd__(self, term):
>       self.value += term.value
>       return self.value

This should be "return self".


>   
>     def __str__(self):
>       return `self.value`

return "Int %i" % self.value

here will make it obvious.

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

a1 += b

is not a shortcut for

a1.__iadd__ (b)

but for

a1 = a1.__iadd__ (b)

with the advantage of a1 evaluated only once.
So, a1 is assumed to be locally available in foo ().

Greetings,

Holger




More information about the Python-list mailing list