Course contentsShow
← Python
Lesson 157 of 1,0603. Functions and ModularizationFree lesson

Returning Functions from Other Functions

You will learn how to return function objects as values, enabling the creation of higher-order functions and dynamic function generation.

In this lesson, you will learn how to treat functions as data by returning them from other functions, allowing you to create "function factories."

Functions as Values

So far, you’ve used return to send back numbers, strings, or lists. In Python, functions are "first-class citizens." This means a function is just another type of object, similar to an integer or a string. Because they are objects, you can return a function from another function just as easily as you return a variable.

When you return a function, you are not calling it (no parentheses); instead, you are passing the function object itself back to the caller.

The "Function Factory" Pattern

Imagine you want a tool that creates specific math functions for you. You can write a "parent" function that builds a "child" function based on the input it receives.

def multiplier_factory(factor):
    def multiply(number):
        return number * factor
    
    return multiply  # We return the function object, not the result of a call

# Create a specialized function
double = multiplier_factory(2)
triple = multiplier_factory(3)

# Use the functions we just created
print(double(5))  # Output: 10
print(triple(5))  # Output: 15

Why Do This?

In the example above, multiplier_factory doesn't just calculate a result; it creates a brand new function tailored to your needs. When double is called, it remembers the factor (which was 2) because the inner multiply function keeps a reference to the environment where it was created.

This technique is incredibly powerful for keeping your code modular. Instead of writing dozens of similar functions, you write one "factory" that spits out exactly the version you need whenever you need it. By returning functions, you move from just calculating data to designing custom tools on the fly.

Key Takeaway: In Python, functions are objects, meaning you can return them from other functions to create dynamic "function factories" that generate specialized behavior.