advancedAdvanced Topics

Decorators

Modify function behavior with decorator patterns.

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 wrapper
5
6@bold
7def greet(name):
8 return f"Hello, {name}"
9
10print(greet("Alice"))
Output
<b>Hello, Alice</b>

02Practical Decorators

Common real-world decorators for timing, caching, and authentication.

Python
1import time
2from functools import wraps
3
4def timer(func):
5 @wraps(func)
6 def wrapper(*args, **kwargs):
7 start = time.time()
8 result = func(*args, **kwargs)
9 elapsed = time.time() - start
10 print(f"{func.__name__} took {elapsed:.4f}s")
11 return result
12 return wrapper
13
14@timer
15def slow_function():
16 time.sleep(0.1)
17 return "Done"
18
19print(slow_function())
Output
slow_function took 0.1002s
Done