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.

Image for post
Image for post

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)

converts any value to a string. 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 adds 3 to the value of and returns the result.

The function contains:

  • A local variable that is set to 3.
  • An inner (or ‘local’) function that adds to the supplied parameter

It uses these to calculate the result of + 3. Of course, you could write a much simpler function to do the same job, we are simply using it to illustrate the idea of inner functions.

The local variable cannot be accessed from outside the function. obviously, since it is a local variable. In a similar way, the inner function can’t be accessed from outside the function either, it is also local. This makes sense, of course, the reason we use local variables and inner functions is to hide the inner workings of our function from the outside world. This is called encapsulation.

It is worth noting that the function is able to access the variable , because they are both within the scope of the outer function .

Functions as objects

As an aside, though quite an important one, you may have heard it said that in Python everything is an object. Well that isn’t just true of numbers, strings, lists etc, it is true of functions too! So:

print(min(1, 2))

calls the function , and prints the result. But without the brackets:

print(min)

will display <built-in function min>, the function object for . You can even assign this function to a variable, and then call it using bracket notation:

a = min
print(a(3, 2))

This will print 2, because references the function object, and calls it. We call this aliasing: is an alias of .

Returning an inner function

Now we will rearrange things a little:

def get_add_3():
n = 3
def f(x):
return x + n
return f
add_3 = get_add_3()
print(add_3(6)) # Prints 9

The first thing to notice here is that returns . It doesn’t call , it returns the function object .

So our new function doesn’t add 3 to a number, instead it returns a function object that adds 3 to a number. This means that we need two steps to add 3 to a number:

  • We call , which returns a function object, which we store as .
  • We then call , which uses the function object to do the calculation.

Now you might have noticed something slightly odd here. is an alias of , and uses the value of , which is a local variable of . But is being called outside the context of , because we have already returned from the call.

Now obviously knows the value of because it knows to add 3 to its arguments. So what is going on?

Well, when the function is returned, Python attaches extra information to the function object, storing the values of any free variables within the outer function.

In fact, this is a closure, it is just that at the moment it isn’t a particularly useful closure.

Closures as function factories

The final step is to make this into something more useful:

def add_n(n):
def f(x):
return x + n
return f
add_4 = add_n(4)
add_7 = add_n(7)
print(add_4(6)) # Prints 10
print(add_7(5)) # Prints 12

This time, when we call , we actually pass in our required value. The function returns a closure of that includes the requested value of .

So creates a function that adds 4 to a value. We can store this in a variable and then call as a function — because that is exactly what it is. Likewise, we can create an function if we need one, or any we require.

Closures are basically function factories, and very useful ones at that.

Why bother?

You might wonder why we would go to all the trouble of creating a closure to add 4 to . Why not just do:

y = x + 4

Well, in functional programming you generally want to deal with functions rather than expressions. Of course we could do this:

def add_4(x)
return x + 4

But that requires us to hand write a function, which could easily introduce bugs. Now assuming we have an closure already defined, and we trust it because it is part of a well tested library, we can just do this:

add_4 = add_n(4)

This is far more declarative — we are saying what we want rather than describing how to do it. It is both more readable and less error prone.

Definition of a closure

To summarise what we have done so far, a closure requires three things:

  • An outer function that contains an inner function.
  • The outer function has parameters and/or local variables.
  • The outer function returns the inner function as a function object.

Example — composing functions

Suppose we wanted to take an object, convert it to a string, and find how long that string is. We could do it like this:

x = len(str(3*10)) # x = 2 because str(3*10) is ‘30’
# and len(‘30’) is 2

That is all very well, but what if we wanted to apply this operation to a list of values using the function. requires a function object and a list or other iterable. So we would have to create a special function:

def lenstr(x):
return len(str(x))
map(lenstr, values)

This would work but is it a very procedural approach. Again, we are defining a special function, which is error prone.

Suppose instead we had a closure, that takes two functions, and and returns a new function that finds :

def compose(f, g):
def comp(x):
return f(g(x))
return comp

is quite a general purpose function, available in several popular Python functional programming libraries. Now we can do this:

lenstr = compose(len, str)

This creates a function without any procedural coding. Or we can just use directly without storing the function:

map(compose(len, str), values)

Again, this is far more declarative. Rather than hand coding a special function, we are simply declaring a function that is a composition of and . It is clearer and more reliable.

Written by

I am a software developer with over 30 years experience in Java, Python and C++. I write for pythoninformer.com.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store