Count Calls with a Decorator
Medium · Decorators
A decorator is a function that takes a function and returns a new one, usually a wrapper that does something extra and then calls the original. Writing @count_calls above def add is the same as add = count_calls(add). Functions are objects, so you can attach attributes to them. Use @functools.wraps(func) on the wrapper so it keeps the original __name__ and __doc__.
Write a decorator count_calls(func). The decorated function must work exactly like the original (any arguments) and have a calls attribute that starts at 0 and goes up by 1 on every call.
The driver run_add is already written: it decorates a fresh add function, calls it once per pair, and reports the results, calls, __name__ and __doc__.