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.
Scope of a Variable. In programming, a variable can be declared and defined inside a class, method, or block. It defines the scope of the variable i.e. the visibility or accessibility of a variable. Variable declared inside a block or method are not visible to outside.
Summary. PHP has four types of variable scopes including local, global, static, and function parameters.
Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can refer (use) it. We can say that scope holds the current set of variables and their values. The two types of scopes are local scope and global scope.
In simple terms, scope of a variable is its lifetime in the program. This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified.
That's documented in Execution model - Resolution of names:
Class definition blocks [...] are special in the context of name resolution. A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace.
(emphasis mine)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With