Medium: Interview Core · Problem 54 of 82

Count the Calls

MediumDecorators and AdvancedPython

Write a decorator counted such that the decorated function keeps working exactly as before (any arguments, same return value) but also has an attribute calls holding how many times it has been called so far.

The decorated function must keep its name and docstring (add.__name__ is still "add"). Different decorated functions have separate counts.

Understand the problem

Think about what @counted really does.

What does @counted above def add(...) mean?

  1. add is called twice
  2. add = counted(add): the name add now refers to whatever counted returned
  3. It adds a comment

The @ line is just a shorter way to write add = counted(add) right after the definition. A decorator receives the function and returns a replacement, usually a wrapper that calls the original.

Why does the wrapper take *args, **kwargs?

  1. To be faster
  2. So that it can accept and pass on whatever arguments the original function takes
  3. Python requires it

The wrapper does not know which function it will wrap, so it accepts any arguments and forwards them unchanged: func(*args, **kwargs).

Without functools.wraps, what is add.__name__ after decoration?

  1. "add"
  2. "wrapper"
  3. "counted"

The name add now points to the wrapper function, whose own name is wrapper. That breaks debugging, logging and documentation tools. @functools.wraps(func) on the wrapper copies the name, the docstring and more from the original.

Write the solution

Write the decorator.

def counted(func):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

Where can you keep the count so that it belongs to this one decorated function and is visible from outside?

Hint 2: the shape of the answer

Define an inner wrapper(*args, **kwargs) that adds 1 to wrapper.calls and returns func(*args, **kwargs). Set wrapper.calls = 0 before returning the wrapper, and decorate the wrapper with functools.wraps(func).

Reflect

Solution

import functools

def counted(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.calls += 1
        return func(*args, **kwargs)

    wrapper.calls = 0
    return wrapper

What this tests: decorators, closures, *args and **kwargs, functools.wraps, and that functions are objects that can carry attributes.

The shape of every decorator: an outer function that takes the function, an inner wrapper that does the extra work and calls the original, and a return wrapper. Once you know it, logging, timing, caching, retrying and access checks are all the same recipe.

Why wraps: it copies __name__, __doc__, __module__ and __wrapped__ to the wrapper. Always use it.

State on the wrapper: a function is an object, so wrapper.calls is just an attribute. The alternative, a counter variable in the outer function, needs nonlocal and cannot be read from outside.

What an interviewer might ask next: Make the count thread-safe. (Protect wrapper.calls += 1 with a threading.Lock: an increment is not atomic.)