Course Content
Mastering Python: Closures and Decorators
Mastering Python: Closures and Decorators
Implementation of Closure
Let's consider the example of closure:
Code Description
- The
outer()
function takes an argumentargument
and defines theinner()
function inside it. - The
inner()
function uses thenonlocal
keyword to indicate that it wants to modify theargument
variable from the enclosing scope (theouter()
function's scope). - The
inner()
function increments the value ofargument
by5
and then returns it. - We create two instances,
variable1
andvariable2
, of theinner()
function with different initial values for theargument
. - When we call
variable1()
, it increments theargument
by5
and returns the new value, which is16
. On the second call tovariable1()
, it increments theargument
again by5
, giving us21
. - Similarly, for
variable2()
, the initial value ofargument
is9
, and the first call increments it by5
, resulting in14
. On the second call tovariable2()
, it increments theargument
again by5
, giving us19
.
The
nonlocal
keyword does not change how the arguments are passed to the function. Instead, it allows the function to access and modify variables in the enclosing scope, which is typically used in nested functions where you want to work with variables from the outer function's scope.In conclusion, the
nonlocal
keyword is not related to function arguments and doesn't provide the ability to change function arguments. Instead, it enables you to access and modify variables from the enclosing (non-local) scope within nested functions.We can operate with the enclosed data: the nonlocal
keyword provides the ability to change argument
(similar to the global
keyword).
Steps to create closure
Step 1:
Create the outer function with its local scope.
Step 2:
Create an inner function with local scope defined inside the outer function.
Step 3:
Access the non-local (outer scope) data from within the inner local scope.
Step 4:
Return the inner function and assign it to the variable.
Step 5:
The local scope of the outer function is removed once it has finished executing.
Step 6:
The inner function returned by the outer function is assigned to the variable and has an enclosing scope with data.
The enclosing scope occupies less memory than the non-local scope because it contains only the dependent values. Enclosed variables/objects do not have names and are represented as memory addresses.
The closure and enclosing scope are commonly used in decorators.
Note
Every time the
outer()
function is called, a newinner()
function is defined.The returned
inner()
functions are distinct and independent objects.
Everything was clear?