Why does the variable name assigned to _to_ affect value lookups?

In python, the following works just fine:

def test_foo():
    class Foo(object):
        pass
    class Fam(object):
        bar = Foo

test_foo()

However, the following is in error NameError: name 'Foo' is not defined:

def test_foo():
    class Foo(object):
        pass
    class Fam(object):
        Foo = Foo

test_foo()

Why does the name that I assign affects the search for an assigned value?

+3
source share
1 answer

The fact that you assign a name Fooinside the class definition makes the name a Foolocal name in this scope (i.e. the scope of the class). Local names are defined statically during parsing and compilation into byte code. When execution reaches approval

Foo = Foo

Python first evaluates the right side. It searches for a local name Foo- as determined at compile time - and does not find it in the local scope. Hence the error.

The same thing happens if you try

def test_foo():
    foo = 3
    class A:
        bar = foo
        foo = 42

test_foo()
+6
source

Source: https://habr.com/ru/post/1792043/


All Articles