"UnboundLocalError: local variable referenced before assignment" Why LEGB rule not applied in this case?

Question:

I am little confused about scoping of variables in Python. Kindly explain difference between below snippets.

class Test(object):
    a_var = 1

    def a_func(self):
        self.a_var = self.a_var + 1
        print(self.a_var, '[ a_var inside a_func() ]')


if __name__ == '__main__':
    t = Test()
    t.a_func()

Output: 2 [ a_var inside a_func() ]

class Test(object):
    a_var = 1

    def a_func(self):
        a_var = a_var + 1
        print(a_var, '[ a_var inside a_func() ]')


if __name__ == '__main__':
    t = Test()
    t.a_func()

Output: UnboundLocalError: local variable 'a_var' referenced before assignment

Why is LEGB rule not applied in second case? Should it not get value from enclosed scope that is class?

Asked By: user3256451

||

Answers:

This might seem weird (and it is), but you don’t get a closure over class, it’s only over def. The “enclosing” scope referred to in LEGB is just talking about function definitions; class blocks don’t count here.

That strange behaviour is an artifact of the way in which classes were added to Python historically. The class scope is not a real scope. Python didn’t always have classes, and the spooky “intermediate scope” just exists during the class definition: internally, the code under the class body is more or less just run through exec under a temporary scope with the result being assigned to the class name. This was a very simple “bolt-on” approach to get OOP into the language, at the time, and it’s also the reason why Python has the explicit self thing as an intentional language design choice.

To access the a_var from the “class scope” from inside a method, you will have to use attribute access via either self.a_var or Test.a_var. Both should work. You may also access it directly at the class level, during the class definition, but since you are still inside the temporary scope that is just another example of a local access (LEGB).

This is documented (albeit not particularly clearly) under the execution model section.

Class definition blocks and arguments to exec() and eval() 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. The namespace of the class definition becomes the attribute dictionary of the class. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes comprehensions and generator expressions since they are implemented using a function scope.

Answered By: wim
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.