Skip to the content

Project: a call-counting decorator

Python · Unit 21: Advanced Python

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. 1. Complete the code

    Fill in the blank so the count keeps climbing between calls.

  2. 2. Write the code

    Write count_calls: before calling the function, print Call 1, Call 2, and so on; then hand back the result as always. Use print("Call", times).

  3. 3. Write the code

    Now the count goes into the dictionary times, with the function's name as the key: f.__name__. run is already written and returns the total and the count; times.clear() empties the dictionary before it starts.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →