Do you remember the
inner function we created in the first lesson on FVP? So, this function was a closure.
A closure function is a function that accesses local variables and uses them in its body in the scope we created it in. It makes closures different from regular functions, which can use only their arguments and global variables.
Let us look at an example demonstrating a closure, and we will use it to show you what it is and how it works:
G = 10 def make_closure(): a = 1 b = 2 def inner(x): return x + G + a return inner
In this example,
inner is a closure:
bvariable is not in the body of
innerand will not be remembered by the closure
- However, the variable
ais involved in generating the result of the
innercall, and therefore we remember its value
- The variable
Gis global if we accept the fact that the specified code is at the top module level and is not nested in any other blocks
By the way, functions created at the top module level, not inside other functions, are not closures. They do not lose anything because all external names visible to these functions are global. It works for imports and definitions from this module located higher in the code.
Memorizing the variable values
We need to mention an important feature: the actual memorization of the value occurs when the scope that the closure was created in ends, as it were, for example, when the current function has finished executing.
The easiest way to think of it is to imagine that when we create the function, we describe the closed variables like they should not forget to remember the current value of the variable
xyz. These items execute the body of the function that created the closure has finished.
Here is an example demonstrating this latest memorization: