Introducing the LEGB Rule
00:01 Whenever you use a name such as a variable or a function name, Python searches through different scope levels to determine whether the name exists or not. To resolve a name, Python follows a specific order of scope levels.
00:15 This order of looking names up is called LEGB rule.
00:20 The LEGB stands for local scope, enclosing scope, global scope, and built-in scope.
00:30 Here is an example. Python looks up a name in a similar way you look for your sunglasses when you want to go out. The sunglasses may be located on your nose already, or they are enclosed in your bag. Otherwise, they may be somewhere in your apartment, and if you can’t find them, then you can use your built-in eyes and squint them awkwardly to avoid the sun. Hmm, does this example make sense, or do you have a better analogy?
00:59 Let me know when the comments below. Okay, analogies aside, let’s get specific about what the scopes—local, enclosing, global, and built-in—mean. See you in the next lesson.
Become a Member to join the conversation.