Codzy

Closures

A function can be defined inside another function, and even returned. The inner function then remembers the variables of the function that created it, even after that function has finished: this is a closure.

So make_multiplier(2) builds a function that multiplies by 2, and make_multiplier(3) another one that multiplies by 3. To change a variable of the enclosing function, the inner function must use nonlocal.

def make_multiplier(factor):
    def multiply(x):
        return x * factor
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5))
print(triple(5))

def make_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter

c = make_counter()
c()
c()
print(c())

Start the lesson