PY-101 ยท Advanced Python
Decorators
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
A decorator is a function that takes another function and returns a new function that adds something before or after it, such as logging or a permission check. Writing @my_decorator above def is shorthand for func = my_decorator(func). Frameworks use decorators everywhere, for example @app.get("/") in FastAPI.
- Pass functions around like values
- Write a wrapper decorator
- Read @decorator syntax
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
from functools import wrapsdef log_calls(func):@wraps(func)def wrapper(*args, **kwargs):print("Calling", func.__name__, args)result = func(*args, **kwargs)print("Returned", result)return resultreturn wrapper@log_callsdef add(a, b):return a + badd(2, 3)print(add.__name__)
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
Calling add (2, 3)
Returned 5
add ๐ฏ Write a decorator shout that makes a function's returned text upper case. With @shout on greet, print(greet("asha")) should show HELLO, ASHA.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
def wrapper(*args, **kwargs): return func(*args, **kwargs).upper(); return wrapper
- The problemYou want to log every time 20 different functions are called. Adding print lines to all 20 is messy. One decorator, written once and placed above each, does it.
- The Python idea
def deco(func):A decorator is a function that takes another function and returns a new function that adds something before or after it, such as logging or a permission check. - In real lifeFastAPI routes are decorators: @app.get("/users") registers the function underneath as the handler for that URL.
Start with a question
You want to log every time 20 different functions are called. Adding print lines to all 20 is messy. One decorator, written once and placed above each, does it.
Web routes, caching, retries, timing and access checks are all decorators in real projects.
Explain it like I'm 10
A decorator is gift wrapping: the present (the function) is unchanged, but now there is a bow and a card around it.
The technical explanation
Functions are values: you can pass them to other functions and return them.
A decorator defines an inner wrapper(*args, **kwargs) that does extra work and calls the original.
@shout above def greet replaces greet with shout(greet).
Syntax
def deco(func):
def wrapper(*args, **kwargs):
...
return func(*args, **kwargs)
return wrapper
@deco
def f(): ... Real-world scenario
FastAPI routes are decorators: @app.get("/users") registers the function underneath as the handler for that URL.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Type hints โQuestions people ask
Are decorators only for functions?
They can wrap classes too (for example @dataclass). The idea is the same: take something, return an enhanced version.
Can I stack decorators?
Yes. Several @ lines stack; the one closest to def is applied first.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner Are decorators only for functions?
They can wrap classes too (for example @dataclass). The idea is the same: take something, return an enhanced version.
beginner Can I stack decorators?
Yes. Several @ lines stack; the one closest to def is applied first.
intermediate @deco above def f is the same as?
f = deco(f). The function is passed to the decorator.
intermediate What does a decorator usually return?
A new wrapper function. It returns the wrapper.
Quick revision
Remember
- Pass functions around like values
- Write a wrapper decorator
- Read @decorator syntax
- Use functools.wraps(func) on your wrapper so the decorated function keeps its real name and docstring.
Syntax
def deco(func):
def wrapper(*args, **kwargs):
...
return func(*args, **kwargs)
return wrapper
@deco
def f(): ... Official documentation
- Function definitions (decorators) (docs.python.org)
- functools.wraps (docs.python.org)