Python decorator recipes
Here are some decorator recipes I have share recently with different colleagues.
Accessing function args
from functools import wraps
def decorator_func(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Decorated func args", args)
print("Decorated func kwargs", kwargs)
func(*args, **kwargs)
return wrapper
@decorator_func("values")
def decorated_fun(a, b, c):
print("Running fn...")
if __name__ == "__main__":
decorated_fun(1, b=2, c=3)
Output:
Decorated func args (1,)
Decorated func kargs {'b': 2, 'c': 3}
Running fn...
Adding arguments to a decorator
from functools import wraps
def decorator_func(decorator_args: list[str]):
def wrapper(fn):
@wraps(fn)
def inner(*args, **kwargs):
print("These are the decorator args", decorator_args)
output = fn(*args, **kwargs)
return output
return inner
return wrapper
@decorator_func(["1", "2"])
def decorated_fun(a, b, c):
print("Running fn...")
if __name__ == "__main__":
decorated_fun(1, b=2, c=3)
Output:
This are the decorator args ['1', '2']
Running fn...