Implementation of ClosureImplementation of Closure

Let's consider the example of closure:

Code Description
Explanation:

  1. The outer() function takes an argument argument and defines the inner() function inside it.
  2. The inner() function uses the nonlocal keyword to indicate that it wants to modify the argument variable from the enclosing scope (the outer() function's scope).
  3. The inner() function increments the value of argument by 5 and then returns it.
  4. We create two instances, variable1 and variable2, of the inner() function with different initial values for the argument.
  5. When we call variable1(), it increments the argument by 5 and returns the new value, which is 16. On the second call to variable1(), it increments the argument again by 5, giving us 21.
  6. Similarly, for variable2(), the initial value of argument is 9, and the first call increments it by 5, resulting in 14. On the second call to variable2(), it increments the argument again by 5, giving us 19.

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 new inner() function is defined.

The returned inner() functions are distinct and independent objects.

Everything was clear?

Section 2. Chapter 2