Decorators
Resources
Decorator with arguments
from functools import partial, wraps
def print_result(func=None, *, prefix=""):
if func is None:
return partial(print_result, prefix=prefix)
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
print(f"{prefix}{result}")
return result
return wrapper
# ---------- #
@print_result
def add(a, b):
return a + b
add(2, 3) # outputs '5'
@print_result()
def add(a, b):
return a + b
add(2, 3) # outputs '5'
@print_result(prefix="The return value is ")
def add(a, b):
return a + b
add(2, 3) # outputs 'The return value is 5'