Decorators
def hello_decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result
return wrapper
@hello_decorator
def add(a, b):
return a + b
if __name__ == '__main__':
output = add(2, 2)
print(output)
- Python Decorators in 15 Minutes | Calm Code Decorators #💻️/⭐ (Private)
- Decorators 101
- Decorators 201
- To get the correct doc strings and indicate that wrapping has occurred on the given function we can use the Functools module with the
wraps
function
- To get the correct doc strings and indicate that wrapping has occurred on the given function we can use the Functools module with the
- Decorators with params
- Useful with using Classes so the extra param passing boiler plate can be avoided
- 3 Essential Decorators in Python You Need To Know
- Can use logging decorators with Functools to log data changes:
from functools import wraps
import datetime as dt
def log_step(func):
@wraps(func)
def wrapper(*args, **kwargs):
tic = dt.datetime.now()
result = func(*args, **kwargs)
time_taken = str(dt.datetime.now() - tic)
print(f"just ran step {func.__name__} shape={result.shape} took {time_taken}s")
return result
return wrapper
Backlinks