← All lessons

Closures

Sign in · Sign up

Lesson 11.6

An inner function "remembers" the variables of the outer one — that's a closure:

def make_counter():
    count = 0

    def inner():
        ...              # change count and return it

    return inner


counter = make_counter()
print(counter())         # 1
print(counter())         # 2

nonlocal is needed to change a variable of the outer function: without it count += 1 would create a new local one. Every call of make_counter() creates its own counter.

The check sets the number calls. Write make_counter() with a closure, save the counter in a variable and call it calls times, printing the result of each call.

Hint

The inner function "sees" the variables of the outer one.

Declare count = 0 in the outer function, and change it inside. You can only change it with nonlocal count, otherwise += creates a new local one. Return the inner function, without calling it.