Python: Closure

By Xah Lee. Date: . Last updated: .

Python 2 does not support closure. See Python: Closure in Python 2

Python 3 supports Closure.

Closure is a feature of programing language design, for functions. Closure is function that carries a environment for all the variables it uses.

Closure is useful when in a situation where a function f returns a function g, and g uses a variable x defined locally in f. Without closure, the x used by g would be gone out of scope.

def f(n):
    # returns a function that computes x ** n
    return lambda x: x ** n

# f(2) returns a function that computes x**2
print(f(2)(4))
# 16

# the returned lambda is a closure. because it maintains the variable n.

Closure used as function with state

# closure example

# ff creates a variable context. It returns a function gg, which uses that context
def ff():
    xx = 0

    def gg():
        nonlocal xx
        xx = xx + 1
        return xx

    return gg

hh = ff()

print(hh())  # 1
print(hh())  # 2
print(hh())  # 3