Learn Python
>>> advanced_python.decorators

Decorators in Python

#concept

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.

#how it works
1

A decorator takes a function, returns a function

That’s the entire shape of what a decorator is.

2

@decorator_name is shorthand

Placed above a function definition, it means function = decorator_name(function).

3

A wrapper function adds the behavior

Defined inside the decorator, running code before and/or after the original function.

4

The wrapper replaces the original

It’s what actually gets called from then on, standing in for the function it wraps.

5

functools.wraps preserves identity

Applied to the wrapper, it keeps the original function’s name and documentation intact.

#example
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_call
def add(a, b):
return a + b
 
print(add(3, 5))
Output
Calling add
add finished
8
1@log_call above add is shorthand for add = log_call(add), replacing add with whatever log_call returns.
2Calling add(3, 5) actually calls wrapper(3, 5), which prints a message, calls the original add function to get the real result, prints another message, and returns that result.
3print(add(3, 5)) shows all three effects in order: the two extra print statements from the wrapper, followed by the actual return value, 8.
#use cases
Adding logging, timing, or caching to a function without touching its own internal code
Enforcing that a function requires authentication or a specific permission, common in web frameworks
Registering a function somewhere (like a route handler in a web framework) through a simple decorator syntax
Retrying a function automatically on failure, wrapping it with retry logic that's reusable across many different functions

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.