Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
What is Closure?
course content

Course Content

Mastering Python: Closures and Decorators

What is Closure?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:

  1. The outer() function was executed once when the inner() function was returned and executed 3 times via variable.
  2. The outer() local scope is removed, but the inner() function has an enclosed non-local variable from the removed outer() local scope.
  3. The interpreter removed the whole outer() scope but left the closed variable from this scope because the inner() 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?

Section 2. Chapter 1
some-alt