A decorator wraps a function to add behaviour (logging, timing, caching, access checks) without changing the function’s own code. You apply one by writing @name above a def. Decorators look magical at first, but they rest on two plain facts: functions can be passed around like any other value, and a function can define and return another function.
In this lesson you will learn
- What the
@syntax actually does - How to write a decorator with a wrapper function
- Why
functools.wrapsmatters - How to write a decorator that takes arguments
- Built-in decorators such as
lru_cacheandproperty
How a Decorator Works
def shout(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper() + "!"
return wrapper
@shout
def greet(name):
return f"hello {name}"
print(greet("rafi"))
# @shout is the same as: greet = shout(greet)
def plain(name):
return f"bye {name}"
plain = shout(plain)
print(plain("nila"))
Output
HELLO RAFI!
BYE NILA!
shoutreceives a function and defineswrapper, which calls the original and changes its result.shoutreturnswrapper, the new improved function.@shoutabovegreetis shorthand forgreet = shout(greet), which the second half of the example does by hand.*args, **kwargslet the wrapper accept whatever arguments the original takes. See Python Functions.
Timing, Arguments and Caching
import functools, time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
value = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {'under' if elapsed < 1 else 'over'} 1 second")
return value
return wrapper
def repeat(times): # decorator with an argument
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@timer
def add(a, b):
return a + b
@repeat(2)
def ping():
print("ping")
print(add(2, 3))
ping()
print(add.__name__)
@functools.lru_cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(60))
Output
add took under 1 second
5
ping
ping
add
1548008755920
@functools.wraps(func)copies the original name and docstring onto the wrapper. Without it,add.__name__would printwrapper.- Decorators with arguments need one extra layer:
repeat(2)returns the real decorator, which then wrapsping. @functools.lru_cacheremembers results. The recursivefib(60)would otherwise make over a trillion calls; with caching it finishes instantly.
Decorators You Will Meet Often
| Decorator | Purpose |
|---|---|
@property | Turns a method into an attribute with optional validation (example) |
@staticmethod | A method that does not need self |
@classmethod | A method that receives the class (cls) instead of the object |
@functools.lru_cache | Caches return values |
@dataclass | Writes __init__, __repr__ and __eq__ for a class |
Common Mistakes
- Forgetting to return the wrapper from the decorator, which replaces your function with
None. - Forgetting to return the result inside the wrapper, so every call returns
None. - Skipping
functools.wraps, which breaks debugging and documentation tools. - Writing
@repeatwithout the brackets for a decorator that expects an argument.
Practice Exercises
Exercise 1. Write a @log_call decorator that prints the function’s name before running it.
Show answer
import functools
def log_call(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("Calling", func.__name__)
return func(*args, **kwargs)
return wrapper
Exercise 2. In what order do stacked decorators run?
Show answer
With @a above @b above def f, Python builds f = a(b(f)). The decorator nearest the function is applied first; the outermost wrapper runs first when you call f.
Frequently Asked Questions
Can a decorator be applied to a class?
Yes. A class decorator receives the class and returns it (or a replacement). @dataclass is the best-known example.
Are decorators only for functions I write?
No. You can wrap any callable, including functions from libraries, by writing new = decorator(old).
Summary
- A decorator takes a function and returns a wrapped version.
@dabovedef fmeansf = d(f).- Use
functools.wrapsto keep the original name and docstring. - Add an outer function to accept decorator arguments.
