LEGB Rules for Python Variables
LEGB is a fundamental concept in Python that defines how variables are found in different scopes.
It stands for:
Local: - The first scope Python checks.
- Contains variables defined within a function or block of code.
- Accessible only within that function or block.
Enclosing: - The scope of any enclosing functions (nested functions).
- Allows inner functions to access variables from their outer functions.
Global: - The module-level scope.
- Contains variables defined outside of any function.
- Accessible from anywhere in the module.
Built-in: - The outermost scope, containing Python's built-in functions and keywords.
Here's how Python uses LEGB to resolve variables:
Local: Python first checks if the variable is defined within the current function or block.
Enclosing: If not found locally, it checks enclosing functions (if any).
Global: If still not found, it looks in the global scope of the module.
Built-in: If not found in any of the above, it checks for built-in names.
Key points to remember:
Variable assignment creates or modifies a variable in the local scope by default.
To modify a global variable from within a function, use the
global
keyword.To modify a variable in an enclosing scope from within a nested function, use the
nonlocal
keyword.
x = 10 # Global variable
def outer_function():
x = 20 # Enclosing variable
def inner_function():
x = 30 # Local variable
print(x) # Prints 30 (local)
inner_function()
print(x) # Prints 20 (enclosing)
outer_function()
print(x) # Prints 10 (global)
#print() - Built in scope
Understanding LEGB is crucial for writing clear, predictable Python code and avoiding errors related to variable scope.