16. A Logging Decorator That Keeps Metadata
Difficulty: Easy · Topic: Functions & decorators
Write a decorator logged. The decorated function works exactly as before, and every call is recorded in a list on the decorated function (add.calls in the sample) as an (args, kwargs) pair: a tuple of the positional arguments and a dict of the keyword ones.
- Each decorated function has its own
callslist. - The decorated function keeps its
__name__and__doc__.
Each call is recorded exactly as it was made: add(1, 2) gives ((1, 2), {}) (two positional, no keyword), and add(5, b=1) gives ((5,), {'b': 1}). (5,) is a tuple with one item, and the default b=0 is not recorded because the caller did not pass it.
Your code runs in CPython on our servers against 4 tests, including hidden ones.
Sample test
@logged
def add(a, b=0):
"Add two numbers."
return a + b
(add(1, 2), add(5, b=1), add.calls, add.__name__)Expected: (3, 6, [((1, 2), {}), ((5,), {'b': 1})], 'add')
Hints
Hint 1
A decorator takes a function and returns a new one, usually an innerwrapper(*args, **kwargs).Hint 2
Functions are objects: you can setwrapper.calls = [].Hint 3
@functools.wraps(func) on the wrapper copies the name, the docstring and more.Learn the concepts
- Decorators · 8 min read. What @ does, wrappers for any function, functools.wraps, and decorators with arguments.
More Python problems
- Counter with a Closure · Easy
- Memoize a Function · Medium
- Time Every Call · Medium
- Retry with Backoff · Hard
- Rate Limiter Decorator · Hard