Count the Calls
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?
addis called twiceadd = counted(add): the nameaddnow refers to whatevercountedreturned- 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?
- To be faster
- So that it can accept and pass on whatever arguments the original function takes
- 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?
"add""wrapper""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.)
VISIBLE = 3
CASES = [
('@counted\ndef add(a, b=0):\n """Add."""\n return a + b\nadd(1)\nadd(2, b=3)\nresult = add.calls', 2, 'the count goes up'),
('@counted\ndef add(a, b=0):\n return a + b\nresult = (add(1, 2), add(5, b=1))', (3, 6), 'the return values are unchanged'),
('@counted\ndef add(a, b=0):\n """Add."""\n return a + b\nresult = (add.__name__, add.__doc__)', ('add', 'Add.'), 'name and docstring are kept'),
('@counted\ndef f():\n pass\n@counted\ndef g():\n pass\nf()\nf()\ng()\nresult = (f.calls, g.calls)', (2, 1), 'separate counts'),
('@counted\ndef f():\n pass\nresult = f.calls', 0, 'zero before the first call'),
('@counted\ndef f(*args, **kwargs):\n return (args, kwargs)\nresult = f(1, 2, x=3)', ((1, 2), {'x': 3}), 'any arguments are passed on'),
('@counted\ndef f(x):\n return 1 / x\nerror_of(f, 0)\nresult = f.calls', 1, 'a call that fails still counts'),
]