Python: Closure

By Xah Lee. Date: . Last updated: .

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

Python 3 supports closure. Practically, a function with local 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

Note the keyword nonlocal. The construct nonlocal varName creates a non-local variable named varName yet isn't global variable. Python will look outward of nested scope to find it.

Python, Function and Class