The LEGB Rule
The interpreter searches for a name from the inside out. This is commonly called the LEGB rule in Python literature. Starting with the local namespace, if you refer to
x inside a function, then the interpreter first searches for it in the innermost scope that’s local to that function.
Next is a situation where
x is just all over the place. One definition is outside
f(), one definition is inside
f() but outside
g(), and a third is inside
g(). Here, the LEGB rule dictates that
g() sees its own local-defined value of
x first, so the
print() function displays
In this final case,
g() will try to print the value of
x is no longer defined anywhere. This causes the interpreter to raise a
NameError exception as soon as the
print() function tries to print
x. When you look closely at the output of the exception, you will notice that the stack trace also follows the LEGB rule. At the bottom, you can see that it started in the function
g(), which is the local scope.
Become a Member to join the conversation.