Exercise: Call counter
Write the kind of decorator interviewers ask for on a whiteboard.
Exercise: write count_calls, a decorator that records how many times the
decorated function has run.
- The wrapped function gets a
callsattribute that starts at0and goes up by one on every call. Functions are objects, sowrapper.calls = 0works. - The wrapper accepts any positional and keyword arguments, passes them on, and returns the original function's result.
- The decorated function keeps its
__name__and__doc__. Usefunctools.wraps. - Each decorated function has its own count.
Inside the wrapper, wrapper.calls += 1 works because wrapper is looked up
when the call happens, after it exists.
If you finish early, try writing retry(times), a decorator with an argument
that calls the function again when it raises an exception.
Press Check to run the tests.