5

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.

4
  • @DeepSpace I'm expecting what evaluation of assignment's right side should be independent to left side's variable name, but this is not the case here. when inside class definition you're doing a = b it gets b from local namespace, but then a = a it gets right a from global namespace Commented Dec 23, 2018 at 19:41
  • Where else would it take a from? Commented Dec 23, 2018 at 19:42
  • From local namespace, please take a look at func0. Commented Dec 23, 2018 at 19:44
  • In my mind it should raise UnboundLocalError like it should in function's namespaces, but for some reasons it doesn't Commented Dec 23, 2018 at 19:45

1 Answer 1

6

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is what I was looking for! Maybe you could provide any insight of motivation to this behavior?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.