Find top 1-on-1 online tutors for Coding, Math, Science, AP and 50+ subjects

Table of Contents

Python Closures


What are Python Closures?

A closure in Python is a nested or inner function that has access to variables within the scope of the enclosing (outer) function. In order to create a “closure” that lasts even after the outer function has returned, it “closes” over the variables it requires from the outer function.

Higher-order functions, or functions that interact with other functions, can only be created with the help of closures. Closures make it possible to create functions that are customized on-the-fly, without requiring additional arguments or complicated logic, by allowing inner functions to access the state of the outer function.

Although they can be a little difficult for beginners to grasp, Python closures are a crucial concept to understand if you want to write complex Python code. Spending some time learning about closures and how they function is a good idea if you’re just getting started with Python programming.

Introduction to Closures in Python

Explanation of Closures:

In Python, a closure is a function that continues to have access to the variables in the scope of the enclosing function even after it has returned. When a nested function makes a reference to a value from the enclosing function, closures are created.

Understanding what, when & why to use closures!

If you want to write a function that can access state that endures across function calls, you should use closures. Iterators, generators, and other higher-order functions can be built using closures. They come in handy when you need to design a function that can be altered depending on an outside state.

Here’s an example:

def make_adder(x): def adder(y): return x + y return adder add5 = make_adder(5) add10 = make_adder(10) print(add5(3)) # Output: 8 print(add10(3)) # Output: 13

In this example, make_adder returns an inner function, adder, which “closes over” the value of x. When we call make_adder(5), we get back a function that adds 5 to its argument. When we call make_adder(10), we get back a function that adds 10 to its argument. We can then use these functions to add 5 or 10 to any number we like.

Scoping Rules and Nested Functions in Python

Overview of Functions:

A function in Python is a section of code that completes a particular task. Functions can accept arguments as inputs and return results in the form of return values. The def keyword is used to define functions, and parentheses are used to call them.

Understanding Inner and Outer Functions:

Functions defined inside of other functions are known as inner functions. The variables in the outer function’s scope are accessible to them, but not the other way around. Functions defined outside of any other function are known as outer functions.

Python Nested Function:

A function that is defined inside another function is referred to as nested. Like inner functions, nested functions have access to the variables in the outer function’s scope. However, nested functions cannot be accessed from outside the outer function and are only defined when the outer function is called.

Here’s an example:

def outer(x): def inner(y): return x + y return inner

Use closure attribute:

In Python, you can use the closure attribute to check if a function is a closure, and to inspect its free variables (the variables it “closes over”). Here’s an example:

/code start./ def make_counter():
    count = 0
    def counter():
        nonlocal count
        count += 1
        return count
    return counter

c = make_counter()
print(c()) # Output: 1
print(c()) # Output: 2

print(c.__closure__) # Output: (<cell at 0x7f9e3c3d6d10: int object at 0x7f9e3c4050c0>,)
print(c.__closure__[0].cell_contents) # Output: 2