Here’s another article in the Functions in Python series. This time about functions returning functions.
If you haven’t read the previous parts yet, feel free to do so. Here they are:
6) Mutable Optional Parameters
8) Arbitrary Number of Positional Parameters
9) Arbitrary Number of Keyword Parameters
10) Arbitrary Number of Both Positional and Keyword Parameters
11) Nested Functions
12) Calling Functions in Other Functions
13) Assigning Functions to Variables
Today we’ll be talking about functions returning functions.
Functions are first-class objects, which means they are objects like any other objects, which further means they can be used just like other objects. Translating this into plain English, we can assign functions to variables and pass them as arguments to other functions. They can also be returned from other functions. If you want to read more about functions as first-class objects, I have an article about that.
And now let’s talk about functions returning functions.
Functions return objects, so they can return functions, which are objects too. Here’s a simple example:
def repeat(n):
def deliver_word(word):
return (word + " ") * n
return deliver_word
quadruple_repeater = repeat(4)
print(quadruple_repeater("hello"))
First we defined a function called repeat that returns another function, called deliver_word. The repeat function takes just one parameter, n, which is then used by the deliver_word function.
The repeat function in our example takes the parameter 4 and returns the deliver_word function, which will use the parameter 4 in its body. Then we assign the returned function to the variable quadruple_repeater. From now on the quadruple_repeater can be used as the deliver_word function. If we pass the word “hello” as its argument, it’ll repeat it 4 times:
hello hello hello hello
We could also create a septuple_repeater like this:
septuple_repeater = repeat(7)
print(septuple_repeater("hi"))
and now the output is:
hi hi hi hi hi hi hi
This topic is closely related to the topic of closures, which I covered in this article, so feel free to read it.