Example of a useful decorator
It prints the arguments of a function and its return values for debugging:
from functools import wraps
def debug(func):
@wraps(func)
def wrapper(*args, **kwargs):
print('Function {} called with args {} and kwargs {}'.format(func.__name__, args, kwargs))
result = func(*args, **kwargs)
print('Function {} returned {}'.format(func.__name__, result))
return result
return wrapper
@debug
def add(x, y):
return x + y
add(1, 2)
Function add called with args (1, 2) and kwargs {}
Function add returned 3