In this section we will learn what closure is and how it works in Python.
Note: we’re assuming you’re familiar with inner functions in python.
What is Closure in Python?
In the inner function section, we mentioned that a function is nothing but an object. So we can declare a function within the body of another function which is known as inner function or nested function.
Also we learned that a function can return another function as its return value and this value can be assigned to another variable or passed as the argument to another function!
But one thing you should always remember is that, a function won’t forget its place of declaration!
This means when we pass a function to another variable or another function, it still uses its scope of declaration to find any necessary variable, etc.
This is called closure.
Let’s see how closure affects the work of a program.
Example: closure in Python
gvar = 400
def parentFuncion():
gvar = 300
def innerFunc():
print(gvar)
return innerFunc
fVar = parentFuncion()
fVar()
Output:
300
In this example we have two variables named gVar. One is declared globally and the other is defined within the body of the parentFunction.
Within the body of the parentFunction we also have an inner function named innerFunc. And this function is returned as a result of calling the parentFunction and assigned to fVar variable.
So now the fVar variable is pointing to the same function that the innerFunc does.
Here’s what happened when we’ve called fVar variable:
1- The execution engine found the body of the function and its enclosing scopes and started to execute the body of the innerFunc .
2- Within the body of this function there’s a call for the gVar variable. So the engine will check the body of the innerFunc for any local variable with the name gVar. But there isn’t one!
3- So the engine will move one step back and checks the enclosing scope of the innerFunc which is the parentFunction! This is where closure shows itself! When working with a function, no-matter where in a program we call the function, the execution always happens in the place where the actual declaration happened. So because the declaration of the innerFunc was in the body of parentFunction, the python execution engine checks this scope for a variable after the body of the innerFunc itself, even though the call to the innerFunc happened in the global scope!
4- So now the engine checks the parentFunction and sees that there’s a variable with the name gVar. So it takes its value and uses it in the body of the innerFunc to be sent to the output stream.
That’s how we got the value 300 on the output.