Python 3: Closure

By Xah Lee. Date: . Last updated: .

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.

[see Python: Closure in Python 2]

Python

Overview

Help

String

Arithmetic

Boolean

Conditional

Loop, Iteration

Data Structure

Function and Class

Module

Misc

Regex

Text Processing

Web

Misc