π Decorators¶
Decorators are functions that wrap other functions to extend or modify their behavior. They are built on higher-order functions and closures.
β Basic Idea¶
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logger
def greet(name):
return f"Hello, {name}!"
Calling greet("Alice") now prints a log and returns the greeting.
β Why Decorators?¶
- Add logging or timing
- Validate inputs
- Cache results
- Enforce permissions
β
Using functools.wraps¶
To preserve the original functionβs metadata (like __name__ and docstring):
from functools import wraps
def logger(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
π Key Takeaways¶
- Decorators wrap functions to add behavior.
- They use higher-order functions and closures.
@decoratoris syntax sugar forfunc = decorator(func).