I'm sure there's a rational explanation for this behaviour, but at the moment is slightly baffling.
class SomeObj: def __init__(self): self.prop = 1 class SomeClass: global objInst def __init__(self): self.reference = objInst self.reference.prop += 1 if __name__ == '__main__': global objInst objInst = SomeObj() clsInst = SomeClass() print "original:" + str(objInst.prop) print "clsInst:" + str(clsInst.reference.prop) # output: # >>> x:2 # >>> y:2
This is all good, and expected: you get a reference to a global object and manipulate it. But what happens if you try to rebind that global name straight in the __init__ method?
[..] class SomeClass: global objInst def __init__(self): self.reference = objInst self.reference.prop += 1 objInst = SomeObj() [..] # output: Traceback (most recent call last): File "test.py", line 16, in
clsInst = SomeClass() File "test.py", line 9, in __init__ self.reference = objInst UnboundLocalError: local variable 'objInst' referenced before assignment
And it gets even more weird! If you move the "global objInst" declaration inside the __init__ method, it works as expected: objInst is bound to a new object with a different state from the one in self.reference. But if you keep the declaration at class level, and simply move the rebinding out in a new method (separated from __init__), you don't get an error but python does not bind the global to a new object.
I guess it's somehow all a matter of context, and it probably makes perfect sense to programming-language scientists; it just doesn't to me :)