For some reasons python gets variable from global namespace when situations like this occurs:
class Cls:
foo = foo
Please look at this code:
foo = 'global'
def func0():
foo = 'local'
class Cls:
bar = foo
print('func0', Cls.bar)
func0()
# func0 local
def func1():
foo = 'local'
class Cls:
foo = foo
print('func1', Cls.foo)
func1()
# func1 global
def func2():
foo = 'nonlocal'
def internal():
class Cls:
foo = foo
print('func2.internal', Cls.foo)
internal()
func2()
# func2.internal global
def func3():
foo = 'local'
class Cls:
bar = foo
foo = foo
print('func3', Cls.bar, Cls.foo)
func3()
# func3 global global
In accordance with PEP 227
A class definition is an executable statement that may contain uses and definitions of names. These references follow the normal rules for name resolution. The namespace of the class definition becomes the attribute dictionary of the class.
but it doesn't look like "following the normal rules" at all to me. What am I missing?
Both Py2 and Py3 operates this way.
a = bit getsbfrom local namespace, but thena = ait gets rightafrom global namespaceafrom?func0.UnboundLocalErrorlike it should in function's namespaces, but for some reasons it doesn't