A decorator is a function that takes another function and returns a new one. You use it to add behaviour—like logging or timing—to existing functions without modifying their code.
The basic structure
def my_decorator(func):
def wrapper():
print('Before')
func()
print('After')
return wrapper
@my_decorator
def say_hi():
print('Hi!')
say_hi()The
wrapper function runs the original code, plus your extra logic. The @my_decorator line is short for say_hi = my_decorator(say_hi): after it, the name say_hi points at the wrapper.Working with any arguments
def my_decorator(func):
def wrapper(*args, **kwargs):
print('Before')
result = func(*args, **kwargs)
print('After')
return result
return wrapper*args and **kwargs let the wrapper take any arguments, so it works on any function.Preserving metadata
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@my_decorator
def say_hi():
print('Hi!')
print(say_hi.__name__)Every function has a
__name__: its name, as text. The last line of the example above prints say_hi. Without the @functools.wraps(func) line, it would print wrapper, the inner function's name. Keeping the real name helps when you're hunting a bug, because error messages and other tools show it.Keeping state on the wrapper
import functools
def counted(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# the wrapper can see itself:
wrapper.call_count += 1
return func(*args, **kwargs)
# set the starting value once:
wrapper.call_count = 0
return wrapper
@counted
def ping():
return 'pong'
ping()
ping()
print(ping.call_count)
# 2
A function in Python is an ordinary object, so you can attach attributes to it. Set the starting value once, after
wrapper is defined but before you return it, and update it inside the wrapper. Because the decorated name now points at wrapper, reading ping.call_count from outside reads that same attribute.