Behind the Scenes of Python Closure Function
Autor: Idego Group

In this article, we will learn what Python closure is, how to use it and what it can be used for. Also, we will explain some extra terms like nonlocal and free variables, what a scope for variables is and what nested and first-class functions are.
A closure is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created.
A function defined inside another function is called a nested function. In Python, the variable can be accessed from inside the scope that it was created. Functions in Python are first-class functions, meaning they can be treated as objects — passed as arguments, assigned, or returned.
A closure example compared to a class-based approach shows that both can achieve similar results. The key difference is how state is maintained. In a class, state is stored as instance attributes. In a closure, state is maintained through free variables — variables not bound to the local scope. Closure keeps binding to free variables that exist when the function is defined.
When working with immutable types in closures, the nonlocal keyword is needed. Without it, reassigning a variable inside the nested function creates a new local variable instead of modifying the enclosed one. The nonlocal keyword makes a variable a free variable and allows changing immutable values stored in closure.
There are three requirements to make a closure: a nested function, access to a free variable, and returning the nested function. Closures are useful when reducing the use of global variables for data hiding, and when implementing simple functions. For more complex tasks, classes and OOP are generally better.
The __closure__ attribute can be used to access values enclosed by a closure, returning a tuple of cell objects whose cell_contents property reveals the stored values.