What is the LEGB Rule in Python: Understanding Variable Scope
LEGB rule in Python defines the order Python follows to find a variable's value: Local, Enclosing, Global, then Built-in scope. It helps Python decide which variable to use when multiple variables have the same name in different places.How It Works
Imagine you are looking for a book in a big library. You first check your desk (local), then the room next door (enclosing), then the whole library (global), and finally the library's reference section (built-in). Python does the same when it looks for a variable's value.
The LEGB rule stands for Local, Enclosing, Global, and Built-in scopes. Python checks these places in order to find the variable you asked for. If it finds the variable in the first place, it stops looking further.
This rule helps avoid confusion when variables with the same name exist in different parts of the program. It ensures Python uses the right value depending on where you are in the code.
Example
This example shows how Python finds the value of x using the LEGB rule.
x = 'global x' def outer(): x = 'enclosing x' def inner(): x = 'local x' print(x) # Prints local x inner() print(x) # Prints enclosing x outer() print(x) # Prints global x
When to Use
Understanding the LEGB rule is useful when you write functions inside other functions or use variables with the same name in different parts of your program. It helps you predict which variable Python will use.
For example, when debugging or organizing code, knowing LEGB helps avoid mistakes like accidentally changing a global variable when you meant to change a local one.
It is also important when using built-in functions or names, so you don't accidentally overwrite them with your own variables.
Key Points
- Local: Variables defined inside the current function.
- Enclosing: Variables in the local scopes of any enclosing functions.
- Global: Variables defined at the top level of the module or declared global.
- Built-in: Names preassigned in Python like
lenorprint. - Python searches these scopes in order and stops at the first match.