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:
def outer(): closed = 222 def inner(): print("Inner starts") print("Inner: non-local variable =", closed) print("Inner ends") inner() print("Outer ends") outer()
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:
def outer(): print("Outer starts") closed = 222 def inner(): print("Inner starts") print("Inner: non-local variable =", closed) print("Inner ends") print("Outer ends") return inner variable = outer()
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:
variable = print variable("Let's print something via variable")
Now pay attention to the outer()
and inner()
functions.
The outer()
function returns the inner()
function, which has a non-local variable:
def outer(): print("Outer starts") closed = 222 def inner(): print("Inner starts") print("Inner: non-local variable =", closed) print("Inner ends") print("Outer ends") return inner variable = outer() # variable = returned inner variable() # returned inner() variable() # returned inner() variable() # returned inner()
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.
Thanks for your feedback!