Skip to content

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 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 1A decorator takes a function and returns a new one, usually an inner wrapper(*args, **kwargs).
Hint 2Functions are objects: you can set wrapper.calls = [].
Hint 3@functools.wraps(func) on the wrapper copies the name, the docstring and more.

Learn the concepts

More Python problems

All Python problems