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

Returning Functions from Higher Order Functions

Learners will master the ability to return new functions from within other functions to implement factory-style programming patterns.

Returning Functions from Higher Order Functions

In this lesson, you will learn how to design "factory functions" that create and return brand-new, customized functions on the fly.

Up until now, you have used higher-order functions to accept functions as arguments. However, Python functions are "first-class objects," which means they can also be treated as return values. When you return a function from another function, you are essentially creating a blueprint that builds a specific piece of logic whenever it is called.

The Power of Function Factories

Imagine you want a tool that creates math operations. Instead of writing separate functions for doubling, tripling, or quadrupling a number, you can write a single "factory" that produces these functions for you.

def multiplier_factory(factor):
    def multiplier(number):
        return number * factor
    return multiplier

# Create specialized functions
double = multiplier_factory(2)
triple = multiplier_factory(3)

print(double(5))  # Output: 10
print(triple(5))  # Output: 15

How it Works

  1. The Outer Function: multiplier_factory acts as the configuration step. It takes the factor and holds onto it.
  2. The Inner Function: multiplier is defined inside. Because of the closure rules you’ve learned, it remembers the factor value even after multiplier_factory has finished executing.
  3. The Return: By returning the multiplier function itself (without parentheses), you are passing back a "ready-to-use" tool that is pre-configured with your specific setting.

This pattern is incredibly powerful because it allows you to dynamically generate logic based on runtime input. You aren't just passing data around; you are passing around the logic itself. This modular approach keeps your code DRY (Don't Repeat Yourself) by allowing you to define a general structure once and instantiate specific variations as needed.

Key Takeaway: By returning a function from an outer scope, you create a factory that generates customized, stateful functions tailored to specific needs.