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
- The Outer Function:
multiplier_factoryacts as the configuration step. It takes thefactorand holds onto it. - The Inner Function:
multiplieris defined inside. Because of the closure rules you’ve learned, it remembers thefactorvalue even aftermultiplier_factoryhas finished executing. - The Return: By returning the
multiplierfunction 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.