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 calls attribute that starts at 0 and goes up by one on every call. Functions are objects, so wrapper.calls = 0 works.
  • 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__. Use functools.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.