Project: a call-counting decorator
Python · Unit 21: Advanced Python
- Full plan
- Python
- Project
- 3 exercises
You are going to write a decorator with a memory. It brings the first two lessons together: the wrapper is a closure, and what it remembers between calls lives in the outer function.
This one lets you through only once.
def only_once(f):
done = False
def wrapper(*args):
nonlocal done
if done:
return "again"
done = True
return f(*args)
return wrapper
@only_once
def enter():
return "welcome"
print(enter(), enter())Prints
welcome again
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Complete the code
Fill in the blank so the count keeps climbing between calls.
2. Write the code
Write
count_calls: before calling the function, printCall 1,Call 2, and so on; then hand back the result as always. Useprint("Call", times).3. Write the code
Now the count goes into the dictionary
times, with the function's name as the key:f.__name__.runis already written and returns the total and the count;times.clear()empties the dictionary before it starts.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.