Decorators in Python
A decorator is a function that takes another function as input and returns a modified or extended version of it, without changing the original function's own source code. Applying @decorator_name directly above a function definition is Python's shorthand for wrapping that function with the decorator's extra behavior automatically.
A decorator takes a function, returns a function
That’s the entire shape of what a decorator is.
@decorator_name is shorthand
Placed above a function definition, it means function = decorator_name(function).
A wrapper function adds the behavior
Defined inside the decorator, running code before and/or after the original function.
The wrapper replaces the original
It’s what actually gets called from then on, standing in for the function it wraps.
functools.wraps preserves identity
Applied to the wrapper, it keeps the original function’s name and documentation intact.
import functools def log_call(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(f"Calling {func.__name__}") result = func(*args, **kwargs) print(f"{func.__name__} finished") return result return wrapper @log_calldef add(a, b): return a + b print(add(3, 5))Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.