Python 3: Closure

By Xah Lee. Date:

Python 3 supports closure. That is, 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

myFun = ff()

print(myFun())  # 1
print(myFun())  # 2
print(myFun())  # 3

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

[see Python: Closure in Python 2]



Text Processing