Closures
Create a counter that remembers its value
A closure is a function that remembers variables from the surrounding function after that function returns. Use it to keep state without putting it in a module-level variable.
func counter():
value = 0
return func():
value += 1
return value
next = counter()
print(next())
print(next())
print(next())
1
2
3
The returned function remembers value. Each call updates the same variable instead of starting over.
Give two counters independent state
Each call to counter() runs the outer function again and creates a fresh value.
func counter():
value = 0
return func():
value += 1
return value
first = counter()
second = counter()
print(first())
print(first())
print(second())
1
2
1
The first counter reaches 2. The second counter starts from its own zero, so its first call returns 1.
A function can read its enclosing module's bindings and update captured bindings owned by enclosing functions. Assignment inside a function creates a local when the only outer binding is at module scope. A closure shares captured cells with its enclosing function and sibling closures. A compound assignment requires an initialized writable binding.