2. Iterators, Generators & Functional Tools

First-Class Functions, Closures & Decorators

Learn how functions work as objects in Python, how closures remember enclosing state, and how to write clean decorators with @functools.wraps and optional parameters.

5 min readUpdated 2026-11-30
In This Lesson
  • Pass and return functions as first-class objects and build lexical closures
  • Write reusable decorators using @functools.wraps to preserve metadata
  • Create parameterized decorators using a three-layer factory function

In frameworks like Flask, FastAPI, Pytest, and Dataclasses, you see @ symbols everywhere: @app.get("/users"), @pytest.fixture, @dataclass. Those are decorators—one of Python's cleanest features for adding cross-cutting behavior (timing, logging, caching, authentication) without cluttering your core business logic.

Why It Matters: Before vs After

Without decorators, adding timing or access logging to 10 functions means duplicating the same start = time.perf_counter() boilerplate inside every single function—making bugs harder to spot and logic harder to test:

python
# Before: timing boilerplate mixed directly into business logic
def compute_tax(amount: float) -> float:
    start = time.perf_counter()
    result = round(amount * 1.08, 2)
    print(f"compute_tax took {(time.perf_counter() - start) * 1000:.2f} ms")
    return result

# After: business logic stays 1 line; timing lives in a reusable decorator
@timer
def compute_tax(amount: float) -> float:
    return round(amount * 1.08, 2)

To understand decorators effortlessly, you only need two building blocks: first-class functions and closures.

How @decorator Wraps Your Function
wrapper(*args, **kwargs)@functools.wraps(func)
1. Before: start timer / validate inputs / log args
2. Original func(*args, **kwargs)__name__ and __doc__ preserved!
3. After: log elapsed ms → return result

Calling greet() enters wrapper(), runs before-logic, calls the original func via @functools.wraps, then runs after-logic.

1. Functions Are Objects & How Closures Capture Variables

In Python, a function is an object just like a string or integer. You can assign it to a variable, pass it as an argument, or return a newly created inner function from an outer function:

python
def make_multiplier(factor: int):
    def multiply(number: int) -> int:
        return number * factor  # Captures `factor` from enclosing scope!
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)

print(double(5))  # 10
print(triple(5))  # 15

Deep Mental Model: How a Closure Remembers State

Normally, when make_multiplier(2) returns, its local variables would vanish. However, Python detects that the inner multiply function references factor from the enclosing scope, so Python packs factor = 2 into a hidden cell object attached to multiply.__closure__:

  • double holds its own cell (factor = 2).
  • triple holds a completely separate cell (factor = 3).
  • If you only read factor, it works automatically. If you want to reassign an outer variable (like count += 1), you must declare nonlocal count inside the inner function—otherwise Python treats count as a brand-new local variable and raises UnboundLocalError!

2. How a Decorator Works Step by Step

A decorator is simply a callable that receives func, defines wrapper(*args, **kwargs) (a closure capturing func), and returns wrapper:

python
import functools
import time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed_ms = (time.perf_counter() - start) * 1000
        print(f"[timer] {func.__name__} took {elapsed_ms:.2f} ms")
        return result
    return wrapper

@timer
def sum_range(n: int) -> int:
    """Return sum from 0 to n - 1."""
    return sum(range(n))

print(sum_range(100_000))

Writing @timer above def sum_range runs at function definition time (import time) and is exact syntactic sugar for:

python
sum_range = timer(sum_range)

Notice two distinct moments in time:

  1. Definition time: timer(sum_range) runs once and rebinds the name sum_range to wrapper.
  2. Call time: Calling sum_range(100_000) actually calls wrapper(100_000), which runs your before-hook, forwards *args, **kwargs to the original func, runs your after-hook, and returns result.
Always Use @functools.wraps(func) AND Return result

Two classic bugs break decorators:

  1. Forgetting @functools.wraps(func) turns sum_range.__name__ into "wrapper" and erases its docstring.
  2. Forgetting return result inside wrapper makes every decorated function silently return None!

3. Decorators That Accept Arguments (3-Layer Factory)

What if you want @repeat(times=3)? Because @repeat(times=3) is evaluated as a function call before wrapping func, you add one outer factory layer:

python
import functools

def repeat(times: int):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            last_result = None
            for _ in range(times):
                last_result = func(*args, **kwargs)
            return last_result
        return wrapper
    return decorator

@repeat(times=3)
def greet(name: str):
    print(f"Hello, {name}!")

greet("Maya")

Trace the three layers from outside in:

  1. repeat(times=3) runs first, stores times = 3 in a closure, and returns decorator.
  2. Python applies @decorator to greet, running decorator(greet) and returning wrapper.
  3. Every call to greet("Maya") executes wrapper("Maya").

Decision Table: Plain vs Parameterized Decorators

PatternSignatureUse When
Plain decorator @timerdef timer(func):Zero configuration needed
Parameterized @repeat(times=3)def repeat(times): def decorator(func):Caller passes settings or thresholds
Stacked @auth + @timerBottom-up wrapping (auth(timer(fn)))Combining orthogonal concerns; note outer runs first at call time

Try It Yourself in the Playground

Python 3Try It Live: Closures & Custom Decorators
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Write a closure make_counter(start=0) that returns a next_id() function. Each call to next_id() should increment count using nonlocal and return the new integer.

Quick Checkpoints

Check Your Understanding

What does @my_decorator placed directly above def process(): actually do?

Check Your Understanding

Why should every wrapper function inside a decorator be decorated with @functools.wraps(func)?