Skip to content
Home » Functions in Python – Functions Returning Functions

Functions in Python – Functions Returning Functions

Spread the love

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:

1) Introduction to Functions

2) Functions with Parameters

3) The return Statement

4) Mandatory Parameters

5) Optional Parameters

6) Mutable Optional Parameters

7) Keyword Arguments

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

14) Functions As Parameters

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.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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.

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply