What Is a Closure?

Get ready to be introduced to closures and learn about the need and benefits of using closures.

We'll cover the following...

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 ...