Decorators - Wrappers That Separate Shared Functionality
What if you want to add shared functionality such as "report errors nicely" / "measure how long it took" to every command? Instead of copy-pasting code every time, you create a wrapper that wraps the function.
python
import time
from functools import wraps
def log_time(func):
"""A decorator that measures and prints a function's execution time"""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time() # record the start time
result = func(*args, **kwargs) # run the original function
end = time.time()
print(f"[Log] {func.__name__} execution time: {end - start:.3f}s")
return result # return the original function's result unchanged
return wrapper
@log_time # ← this one line automatically adds timing to run_summary
def run_summary():
...- You only need to add the single line
@log_time. The original function's code is left untouched - Requirement: implement at least 1 decorator for exception handling/logging/timing and actually apply it
Summary
| Concept | Summary |
|---|---|
| Decorator | A wrapper that layers extra functionality onto a function |
Source: Codyssey-B1/B2-1
