🔶 Python: Decorators
A decorator wraps a function to add behavior without modifying it.
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time()-start:.2f}s")
return result
return wrapper
@timer # Same as: process_data = timer(process_data)
def process_data(df):
return df.groupby('category').sum()
What @timer actually does: Replaces process_data with wrapper, which calls the original function but adds timing around it.
Common decorators you've seen:
- @staticmethod, @classmethod — modify method behavior
- @property — make a method accessible like an attribute
- @functools.lru_cache — memoize function results