Python Basics - 11. Scope, Closures, and Decorators

This notebook explains variable scope (LEGB), closures, and decorators. These topics are key to understanding how Python functions behave in real projects.

Download Notebook

Download this notebook

1. LEGB Scope Rule

Python resolves names in this order: Local, Enclosing, Global, Built-in.

message = "global"

def outer():
    message = "enclosing"
    def inner():
        message = "local"
        print(f"Inner sees: {message}")
    inner()
    print(f"Outer sees: {message}")

outer()
print(f"Global sees: {message}")
Inner sees: local
Outer sees: enclosing
Global sees: global

2. Closures

A closure is an inner function that remembers values from its enclosing scope even after the outer function returns.

def make_multiplier(factor):
    def multiply(x):
        return x * factor
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(10), triple(10))
20 30

3. Decorators

A decorator wraps a function to add behavior before/after execution without changing the original function body.

def log_call(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@log_call
def add(a, b):
    return a + b

add(5, 7)
Calling add with args=(5, 7), kwargs={}
add returned 12
12