🌱 Junior Track 10 of 10

10. Scope & Namespaces

Master variable resolution & symbol isolation: `Local scope`, `Enclosing scope`, `Global scope`, `Built-in scope`, the `LEGB rule`, scope modifiers (`global` & `nonlocal`), and runtime namespace inspection (`locals()` & `globals()`).

👁️ Views: 0
# ==============================================================================
# JUNIOR PYTHON TRACK 10 — SCOPE & NAMESPACES (LEGB RULE)
# ==============================================================================

# G: Global Scope Variable
global_counter: int = 100

def outer_function():
    # E: Enclosing Scope Variable
    enclosing_val: str = "Enclosing Scope"
    
    def inner_function():
        # L: Local Scope Variable
        local_val: str = "Local Scope"
        
        # Modifying Enclosing Scope variable with nonlocal
        nonlocal enclosing_val
        enclosing_val = "Modified Enclosing Scope"
        
        # Modifying Global Scope variable with global
        global global_counter
        global_counter += 1
        
        return {
            "local": local_val,
            "enclosing": enclosing_val,
            "global": global_counter,
            "builtin_len": len([1, 2, 3])  # B: Built-in Scope function
        }
        
    res = inner_function()
    return res, enclosing_val

def inspect_namespaces():
    """Demonstrates runtime namespace inspection via locals() & globals()."""
    x = 42
    y = "Python"
    local_dict = locals()  # Returns dictionary of local namespace symbol table
    return f"Local Namespace keys: {list(local_dict.keys())}"

if __name__ == "__main__":
    print("--- LEGB Scope Resolution ---")
    result, updated_enclosing = outer_function()
    print(f"Inner Function Result: {result}")
    print(f"Updated Global Counter: {global_counter}")
    print(inspect_namespaces())
🌱 Junior Track 10 Master Reference

10. Python Scope, Namespaces & LEGB Resolution Rule

1️⃣ The LEGB Resolution Pyramid

When Python encounters a variable name, it searches through four distinct scope levels in strict order:

[L]ocal Scope         --> Inside current function
[E]nclosing Scope     --> Inside outer enclosing functions (closures)
[G]lobal Scope       --> Top-level module file
[B]uilt-in Scope     --> Built-in Python keywords & functions

2️⃣ Local Scope (`L`)

Variables assigned inside a function belong exclusively to that function's local scope. They are created when the function is invoked and destroyed upon return.

def calculate_tax(amount):
    rate = 0.2 # 'rate' is Local to calculate_tax
    return amount * rate

3️⃣ Enclosing Scope (`E`) & `nonlocal` Keyword

Enclosing scope exists in nested functions. To modify an outer function's variable from an inner function, use the nonlocal keyword.

def make_counter():
    count = 0 # Enclosing variable
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

4️⃣ Global Scope (`G`) & `global` Keyword

Global variables are declared at module file level. To modify a global variable inside a function body, you must declare it using global.

app_status = "STARTING" # Global variable

def set_ready():
    global app_status
    app_status = "READY"

5️⃣ Python Namespaces (`locals()` & `globals()`)

A Namespace is a dictionary mapping variable names (keys) to objects (values). You can inspect runtime namespaces using built-in functions:

print(locals()) # Dictionary of local variable name-to-object bindings
print(globals()) # Dictionary of module-level global bindings

⭐ Rate Track 10: Scope & LEGB Rule (1 to 5 Stars)

Your rating is stored directly in the database. Average: 5.0 / 5 (1 rating)

★ ★ ★ ★ ★
← 9. *args & **kwargs 🌱 Junior Hub 11. OOP →