mingaleg
mingaleg

Reputation: 2087

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.

Upvotes: 5

Views: 90

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

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)

Upvotes: 6

Related Questions