Episode 25 of 29
Decorators
Understand decorators — a powerful Python feature for modifying function behavior.
Decorators modify or enhance functions without changing their code.
Basic Decorator
def my_decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# Before function
# Hello!
# After functionPractical Example — Timer
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Took {end - start:.4f}s")
return result
return wrapper