Skip to main content
Albero Academy

Decorators & Closures

Functions as first-class values, closures that capture state, and decorators that wrap behaviour — the magic behind @ syntax.

Chapter 15Python17 min readBeginner friendly
  • #Python
  • #Decorators
  • #Closures

The @ symbol you see above functions in Django, Flask, FastAPI and pytest is a decorator — a function that wraps another function to add behaviour. To understand decorators you first need two ideas: functions are first-class values, and closures remember their surroundings. This chapter builds up to writing your own.

Functions are values

In Python a function is an ordinary object. You can assign it to a variable, pass it as an argument, and return it from another function — exactly like a number or string:

first-class functions
def shout(text):
return text.upper()
f = shout # assign — no parentheses
print(f("hi")) # HI
def apply(fn, value):
return fn(value) # pass a function in
print(apply(shout, "hello")) # HELLO

Closures

A closure is a function that remembers variables from the scope where it was created, even after that scope has finished. An outer function can build and return a customised inner function:

a closure
def multiplier(factor):
def multiply(n):
return n * factor # 'factor' is remembered
return multiply
double = multiplier(2)
triple = multiplier(3)
print(double(10)) # 20
print(triple(10)) # 30

Decorators

A decorator is just a function that takes a function and returns a new function wrapping it. The @name syntax above a definition is shorthand for "reassign this function to name(this_function)":

your first decorator
def logged(fn):
def wrapper(*args, **kwargs):
print(f"calling {fn.__name__}")
result = fn(*args, **kwargs)
print(f"{fn.__name__} returned {result}")
return result
return wrapper
@logged # same as: greet = logged(greet)
def greet(name):
return f"Hi {name}"
greet("Aanya")
# calling greet
# greet returned Hi Aanya

The *args, **kwargs in the wrapper let it wrap any function regardless of its signature. Common real uses: logging, timing, caching, access control, retries.

Preserving metadata

Wrapping replaces the original function, so greet.__name__ becomes "wrapper" — which breaks debugging and docs. functools.wraps copies the original's identity onto the wrapper:

functools.wraps
from functools import wraps
def logged(fn):
@wraps(fn) # keep fn's name, docstring, etc.
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper

Decorators with arguments

To pass options to a decorator (like @retry(times=3)), add one more layer — a function that returns a decorator:

a configurable decorator
from functools import wraps
def repeat(times):
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
for _ in range(times):
result = fn(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(times=3)
def ping():
print("ping")
ping() # prints ping three times

Practice

Write a timer decorator that prints how long the wrapped function took (use time.perf_counter() and @wraps). Then write a repeat(n) decorator-with-arguments and apply both to a function.

Key takeaways

  1. 01Functions are first-class values: assign, pass and return them like any object.
  2. 02A closure is an inner function that remembers variables from where it was created.
  3. 03A decorator takes a function and returns a wrapped one; @name is shorthand for name(fn).
  4. 04Use *args/**kwargs in the wrapper to decorate any signature, and @wraps to keep the original identity.
  5. 05For decorator arguments (@retry(3)), add an extra layer: a function that returns the decorator.