Python Glossary Русский

all Python 3Functionsterm

Closures

closures

A nested function captures a variable from the enclosing scope. Used for function factories and to encapsulate state.

Syntax

def outer():
    x = 10
    def inner():
        return x
    return inner

The classic trap: a closure captures the variable itself, not its value at creation time. So functions built in a loop (lambda: i) all see i's final value — pin it with a default argument (lambda i=i: i). And to rebind, rather than just read, a captured variable, the inner function needs nonlocal.

Examples

def make_adder(n):
    def adder(x):
        return x + n
    return adder
add5 = make_adder(5)
print(add5(3))  # → 8
def make_multiplier(factor):
    def multiply(x):
        return x * factor
    return multiply
double = make_multiplier(2)
print(double(7))  # → 14
def counter():
    count = 0
    def inc():
        nonlocal count
        count += 1
        return count
    return inc
c = counter()
print(c(), c())  # → 1 2
def make_greeting(greeting):
    def greet(name):
        return f'{greeting}, {name}!'
    return greet
hello = make_greeting('Hello')
print(hello('Bob'))  # → Hello, Bob!
# Проверка замыкания
def outer():
    x = 'closure'
    def inner():
        return x
    return inner
f = outer()
print(f())  # → closure
# __closure__
def make_pow(n):
    def power(x):
        return x ** n
    return power
p = make_pow(3)
print(p(2))  # → 8
print(p.__closure__[0].cell_contents)  # → 3

See also

Open in the full glossarydocs.python.orgReport an inaccuracy