Read/Write Python Closures

To expand on Ignacio’s answer:

def counter():
    count = 0
    def c():
        nonlocal count
        count += 1
        return count
    return c

x = counter()
print([x(),x(),x()])

gives [1,2,3] in Python 3; invocations of counter() give independent counters. Other solutions – especially using itertools/yield are more idiomatic.

Leave a Comment