The LEGB Rule
00:00
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.
00:26
If x
isn’t in the local scope but it appears in a function that resides inside another function, then the interpreter continues its search in the enclosing function’s scope.
00:42
If x
is not found in the local nor the enclosing scope, then the interpreter looks in the global scope.
00:53
If x
is not in the global scope either, then the interpreter finally tries the built-in scope. If the interpreter is unable to find the declaration in any of the scopes, it raises a NameError
.
01:10
Let’s have a look at some examples of the LEGB rule. In each example, the innermost enclosed function g()
will attempt to display the value of a variable named x
to the console.
01:25
In the first example, x
is defined only in one location. It’s outside both f()
and g()
, so it resides in the global scope.
01:37
That means the print()
function within the function g()
can refer to only one possible x
. It displays the x
object defined in the global namespace, which is the string "global"
.
01:54
In the next example, x
will be defined in two places—one outside f()
still in the global scope and one inside f()
but outside g()
, which is the enclosing scope.
02:11
So now according to the LEGB rule, the interpreter finds the value from the enclosing scope before looking at the global scope, so the print()
function displays enclosing
instead of global
.
02:28
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 local
.
02:58
In this final case, g()
will try to print the value of x
, but 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.
03:35
Next, it tried to find x
in the function f()
, which is the enclosing scope. And finally, the interpreter looks in the module, which is the global scope.
03:48 And that concludes this section about scopes.
03:52 In the next section of this course, you will learn how to modify variables that are out of scope.
Become a Member to join the conversation.