Search⌘ K
AI Features

What Is a Closure?

Explore the concept of closures in Python functional programming. Understand how inner functions can be returned and combined with local variables to form closures. Learn to create dynamic, reusable functions that retain state and customize behavior through closures.

In functional programming, we sometimes write functions that create other functions. A simple and elegant way to do this is to use a closure. Closures provide a way to create functions dynamically, a little like lambdas but far more powerful.

Inner functions

Let’s start by looking at inner functions. An inner function is a function that is defined inside another function. Here is an example:

Python 3.8
def print3():
def print_hello():
print('hello')
print_hello()
print_hello()
print_hello()
# Main code
print3()
print_hello() # This will give an error

print_hello is an inner function of print3. Specifically, print3 first defines print_hello, then calls it three times.

The result when we run the main code is:

  • Calling print3 prints “hello” three times.
  • Calling print_hello gives an error because it is only visible from inside print3.

Returning an inner function

A ...