Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Implementation of Closure | Closure
Mastering Python: Closures and Decorators
course content

Course Content

Mastering Python: Closures and Decorators

Implementation of Closure

Let's consider the example of closure:

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
We're sorry to hear that something went wrong. What happened?
some-alt