Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
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.
00:10 To resolve a name, Python follows a specific order of scope levels. 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.
00:44 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.
00:54 Hmm, does this example make sense, or do you have a better analogy? 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.
Become a Member to join the conversation.