Understanding Python Decorators
Ad
What is a Decorator?
A decorator is a function that wraps another function to add behaviour — without changing the original function's code. You apply it with the @ syntax.
The Simplest Decorator
def log(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log
def greet(name):
return f"Hello {name}"
greet("Sara") # prints "Calling greet" then returns "Hello Sara"
A Practical Timer Decorator
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time()-start:.4f}s")
return result
return wrapper
@timer
def slow():
time.sleep(1)
Common Built-in Decorators
@staticmethod/@classmethod— method types in classes.@property— turn a method into a read-only attribute.@functools.cache— memoise expensive functions.
FAQs
Why use *args and **kwargs?
So the wrapper works with any function signature. More in our Python guides.
What does functools.wraps do?
It preserves the original function's name and docstring on the wrapper. Always add it to decorators.
