Skip to main content

Command Palette

Search for a command to run...

LEGB Rules for Python Variables

Published
2 min read
K

A skilled construction professional specializing in MEP projects. Armed with a Master's degree in Data Science, seamlessly combines hands-on expertise in construction with a passion for Python, NLP, Deep Learning, and Data Visualization. While currently at a basic level, dedicated to enhancing data skills, envisioning a future where insights derived from data reshape the landscape of construction practices. With a forward-thinking mindset, building structures but also shaping the future at the intersection of construction and data.

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.

More from this blog

Data Ilm - Data to Knowledge Discovery

47 posts

Mechanical engineer turned data scientist, passionate about unraveling insights from data and sharing knowledge