Decorators
Resources
- Practical Decorators: Pycon 2019
- Making your Python decorators even better, with functool.wraps
- How To Test Python Decorators? How To Bypass A Decorator?
- Python Decorator Tutorial with Example (has examples of decorators with arguments)
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'
Backlinks
Python
- [[03-decorators]]