This is required due to Python's semantics. You can't optimize that away unless the code is written to explicitly turn a global into a local.
class A:
def __init__(self, value=0):
self.b = value
def __str__(self):
if self.b == 0:
global a
a = A(1)
elif self.b == 1:
import __builtin__, __main__
__builtin__.a = 2
del __main__.a
return str(self.b)
a = A()
def foo():
print a
print a
print a
foo()
This generates: 1
2
3
but it's a different 'a' in all three cases; the last isn't even from the module's namespace.Yes, the output was from my first version. I rewrote it to be more explicit about changing the 'a' each time, and forgot to update the output section.