Function Decorators
Modify or enhance function behavior dynamically without altering the original function code.
Learning objectives
- Understand closures and higher-order functions
- Write custom @decorator functions to log or timing wrap calls
Lesson material
Decorator Pattern
A decorator takes a function as argument and returns a replacement function wrapper.
Example code
def log_call(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}...")
res = func(*args, **kwargs)
print("Done!")
return res
return wrapper
@log_call
def add(a, b):
return a + b
print(add(4, 6))
Practice exercise: Uppercase Decorator
Write a decorator `uppercase_result` that converts the string returned by the decorated function into uppercase. Apply it to `def get_msg(): return "hello"`. Print `get_msg()`.