Python 3: Closure

By Xah Lee. Date:

Python 3 supports closure. That is, a function with local state.

# -*- coding: utf-8 -*-
# python 3

# 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. 7. Simple statements — Python v3.3.3 documentation #the-nonlocal-statement

[see Python: Closure in Python 2]

If you have a question, put $5 at patreon and message me.