Overview
Add behaviour to any function without changing its code — the pattern behind logging, caching and access checks.
- Functions are objects
- Wrapper functions and *args / **kwargs
- The @decorator syntax
- functools.wraps
Short Course
A decorator is a function that takes a function and returns a new one
that wraps it. @timer above a def is shorthand for f = timer(f).
Use functools.wraps so the wrapper keeps the original's name.
import functools
def announce(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("calling", func.__name__)
return func(*args, **kwargs)
return wrapper
@announce
def add(a, b):
return a + b
add(2, 3) # prints "calling add", returns 5
Task
Write a decorator shout that calls the wrapped function and returns its
result in UPPERCASE. It must pass through any positional and keyword
arguments, and keep the function's __name__.
Test Suites
Pending
Stdout