Closures

Learn how closures extend the scope of a function.

We'll cover the following

Nested functions

Before getting acquainted with closures, let’s get a thumbnail of nested functions.

We discussed nested functions in detail previously. They can access variables of the enclosing scope. We cannot access the non-local values outside their scope. Let’s look at an example:

def outer(parameter):
    def inner():
        print(parameter)
    inner()

Here, the inner() that uses parameter as a non-local variable can be accessed inside outer(), but not outside the body of outer().

What is closure?

A closure is a function that remembers the variables in the enclosing scope, even if they’re not in the memory. In simple words, the inner function has its scope only inside the outer function. But with the use of closures, we can easily extend its scope to invoke a function outside its scope. Let’s see how to do it.

Get hands-on with 1400+ tech skills courses.