Course Content
Mastering Python: Closures and Decorators
Mastering Python: Closures and Decorators
What is Closure?
Note
The previous section (Scopes) is important to learn closure and decorators.
Earlier, we discussed the non-local scope. Now, let's learn how to convert it into an enclosing scope.
You know that function scope is created when the function is called and is deleted when the function ends execution:
The closed
variable and inner()
function are placed inside the outer()
local scope.
Let's return the inner()
function and assign it to the global variable:
The inner()
function is not executed, but the outer()
function ends executing and returns the inner()
function.
Note
The
inner()
function in return written without parentheses (()
) that means this function is not called.To return the function, you should write just the function name (without calling).
A function is an object. You can assign the function to the variable:
Now pay attention to the outer()
and inner()
functions.
The outer()
function returns the inner()
function, which has a non-local variable:
In the example above, we can see that:
- The
outer()
function was executed once when theinner()
function was returned and executed 3 times viavariable
. - The
outer()
local scope is removed, but theinner()
function has anenclosed
non-local variable from the removedouter()
local scope. - The interpreter removed the whole
outer()
scope but left theclosed
variable from this scope because theinner()
function has a reference to this variable.
This phenomenon is named closure.
Note
Enclosing scope is a removed non-local scope where objects can be left with references from other scopes.
When outer()
is called, a new outer()
local scope will be created that is independent of the previous one. Every returned inner()
function is unique, has its enclosing scope, and is not dependent on other returned inner()
functions.
Everything was clear?