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.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 13 views 0 copies

Python code

18 lines
Python 3.9+
def 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

stdout
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

  1. Use a decorator syntax with `@compose(double, add_one)` for reusable composition.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.