A decorator is a function that takes another function and extends its behaviour without changing its code. Apply it with @decorator_name above a function.
Decorators are used for logging, timing, caching, access control and more. Frameworks like Flask use them for routes: @app.route("/").
💡 Key Takeaways: Python Decorators
Mastering Python Decorators helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
Python Decorators Code Example
Python
import time
from functools import wraps, lru_cache
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {(time.perf_counter() - start) * 1000:.2f} ms")
return result
return wrapper
@lru_cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
@timer
def compute():
return fib(200)
print(compute())
Free sign-in required · Google login available
Python Decorators Practice Exercises
Check what you learned in “Python Decorators”.
/ 3 solved
Fill in the blank
Apply the decorator to the function.
def work():
pass
✓ Correct!Not quite. Try again.
Multiple choice
What is a decorator?
✓ Correct!Not quite. Try again.
Code challenge
Write a decorator shout that makes the wrapped function's result upper case. Decorate hello() (returns "hi") and print hello().
Write the code in the live editor. Your answer is checked automatically.