LEGB Rules for Python Variables

·

2 min read

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:

  1. Local: Python first checks if the variable is defined within the current function or block.

  2. Enclosing: If not found locally, it checks enclosing functions (if any).

  3. Global: If still not found, it looks in the global scope of the module.

  4. 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.

Did you find this article valuable?

Support K Ahamed by becoming a sponsor. Any amount is appreciated!