Member-only story
Closures in Python
Closures are a powerful and flexible way to create new functions out of existing functions. You can think of them as being function factories, that can create new functions according to a template and one or more parameters.
In this article we will look at how to use a closure to compose two functions, as a simple illustration of why and how we use closures.
This article first appeared on pythoninformer.com. The topic is covered in more detail in my e-book Functional Programming in Python.
Composing functions
Composing two functions simply means applying one function to the result of another. For example, consider these two standard Python functions:
str(x)
len(x)
str(x)
converts any value x
to a string. len(x)
returns the length of any sequence x. The composition of these two functions is
Inner functions
An inner function is a function that is defined within the scope of another function, like this:
def add_3(v):
n = 3
def f(x):
return x + n
return f(v)print(add_3(6)) # Prints 9
In this case our outer function add_3
adds 3 to the value of x
and returns the result.