Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable scopes inside class definitions are confusing

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.

like image 320
mingaleg Avatar asked Dec 23 '18 19:12

mingaleg


People also ask

Is scope of variable within a class?

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.

What are the 4 different types of scopes that a variable can have?

Summary. PHP has four types of variable scopes including local, global, static, and function parameters.

What are the 2 different types of scopes of variables explain with an example?

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.

What is variable scope explain in detail?

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.


1 Answers

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)

like image 92
Thierry Lathuille Avatar answered Oct 18 '22 22:10

Thierry Lathuille