advancedAdvanced Topics
Decorators
Modify function behavior with decorator patterns.
In this lesson
01What Are Decorators?
Decorators are functions that take another function and extend its behavior without modifying it.
Python
1def bold(func):2 def wrapper(*args, **kwargs):3 return f"<b>{func(*args, **kwargs)}</b>"4 return wrapper56@bold7def greet(name):8 return f"Hello, {name}"910print(greet("Alice"))
Output
<b>Hello, Alice</b>
02Practical Decorators
Common real-world decorators for timing, caching, and authentication.
Python
1import time2from functools import wraps34def timer(func):5 @wraps(func)6 def wrapper(*args, **kwargs):7 start = time.time()8 result = func(*args, **kwargs)9 elapsed = time.time() - start10 print(f"{func.__name__} took {elapsed:.4f}s")11 return result12 return wrapper1314@timer15def slow_function():16 time.sleep(0.1)17 return "Done"1819print(slow_function())
Output
slow_function took 0.1002s Done