How to Compose Two Functions into a Single Callable in Python
Combine two Python functions into a single callable using a compose helper, then apply the chained call.
Python code
18 linesdef add_one(x):
return x + 1
def double(x):
return x * 2
def compose(f, g):
return lambda x: f(g(x))
add_then_double = compose(double, add_one)
double_then_add = compose(add_one, double)
result1 = add_then_double(5)
result2 = double_then_add(5)
print(f"add_one then double(5) = {result1}")
print(f"double then add_one(5) = {result2}")
print(f"Add requires one arg, compose chains two functions: {type(add_then_double).__name__}")
Output
add_one then double(5) = 12
double then add_one(5) = 11
Add requires one arg, compose chains two functions: function
How it works
The compose function returns a lambda that applies the second function g first, then passes the result to f. This creates a new callable that behaves like a single function. The order matters: compose(double, add_one) means add_one runs first, then double. The lambda captures the functions f and g from the enclosing scope, allowing the composed callable to be reused. This pattern is a classic way to build pipelines without nesting calls manually.
Common mistakes
- Reversing the argument order in compose and accidentally calling f before g.
- Assuming compose mutates the original functions instead of returning a new callable.
- Forgetting that the composed callable still needs an argument when you call it.
Variations
- Use a decorator syntax with `@compose(double, add_one)` for reusable composition.
- Chain more than two functions by nesting compose calls, e.g., compose(f, compose(g, h)).
Real-world use cases
- Building a data transformation pipeline that applies data cleaning then feature scaling.
- Creating middleware in web frameworks that chains request processing steps.
- Constructing math functions for functional programming patterns in finance models.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.