Scope rule pecularities

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


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
  
    def __str__(self):
      return `self.value`
  
  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.

-- 
Antoon Pardon



More information about the Python-list mailing list