Command Palette

Search for a command to run...

Hectal
Phase 9: Iterators, Generators and Decorators
Python · Exercise 4 of 6 PreviousNext
Intermediate

Write a call-counting decorator

Write a decorator count_calls that counts how many times the decorated function has been called. The count must be readable as function.calls (starting at 0). The decorated function must keep its name and docstring, and pass all arguments through and return the result.

Decorate def add(a, b=0) (docstring "Add two numbers."), call it twice, and print add.calls.

What Check tests

  1. The decorated function still returns its result
  2. Keyword arguments are passed through
  3. calls goes up by one for each call
  4. The name and docstring are kept
  5. Two decorated functions have separate counters
  6. The program prints 2

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.