Python 3: Closure

By Xah Lee. Date:

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

# 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.

[see Python: Closure in Python 2]

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

Python 3

Lang Detail

  1. Print Version String
  2. Quoting String
  3. String Operations
  4. Format String
  5. Operators
  6. Object, ID, Type

Misc

  1. Traverse Directory
  2. Sort List, Matrix, Object
  3. Python 3: Map with Side Effect Doesn't Work If Result is Not Used
  4. Python 3 Closure
  5. Python 2 and 3 Difference