Python & FastAPI•Part 2: Python Core Language, Internals & Runtime (6 - 25)
Python Decorators and `functools.wraps`:
In Simple Words:
A decorator is a function that takes another function, wraps its behavior, and returns a new function. functools.wraps is essential to preserve the original function's name (__name__) and docstring.
python
import functools, time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
duration = time.perf_counter() - start
print(f"{func.__name__} took {duration:.4f}s")
return result
return wrapper
@timer
def compute():
return sum(range(1_000_000))