linkedinlogo
Python
Python

Explain Closures and Implement a Function Factory with State

December 3, 2025

Closures in Python are functions that capture and remember variables from their enclosing scope, allowing them to maintain state. A function factory uses closures to create customizable functions with internal state that can be retained and modified across calls.

A closure captures outer function variables, enabling state retention in inner functions. Function factories generate these configurable functions that maintain private state without using classes.

Code

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

c = counter_factory()
print(c()) # 1
print(c()) # 2
bg-image
Company Deck
PDF, 3MB

© 2026 Zignuts Technolab. All Rights Reserved.