- Courses
- đ»Programming Languages
- đPython
- Functional Programming
- Function Composition
On this page
Function Composition in Python: A Functional Programming Guide
Published on July 6, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Function composition is one of the most fundamental concepts in functional programming â yet it is often overlooked in Python education. At its core, composition is the process of combining two or more functions to produce a new function. In mathematical terms, if you have functions f(x) and g(x), their composition f â g is defined as f(g(x)). The output of g(x) becomes the input for f(x). This simple idea transforms how you structure code: instead of writing long, monolithic procedures that do everything at once, you break your logic into small, focused functions and compose them together. The result is code that is more readable, more reusable, easier to test, and better aligned with the principles of functional programming. While Python does not have built-in function composition operators, the language's support for higher-order functions and the functools module make composition both natural and powerful.
What Is Function Composition?â
Function composition is the process of taking two or more functions and combining them into a single function that applies them in sequence. The output of each function becomes the input for the next.
Consider two simple functions:
def add(x):
return x + 2
def mul(x):
return x * 2
To compute the result of applying add then mul, you would write:
res = mul(add(5)) # add(5) = 7, then mul(7) = 14
This is function composition in its simplest form â you are composing mul and add into a new operation. However, manually nesting function calls like this becomes unwieldy as the number of functions grows.
Mathematical Notationâ
In mathematics, the composition of two functions f and g is written as (f â g)(x) = f(g(x)). The function g is applied first, then f. The order matters: composition is not commutative. f â g is not the same as g â f.
Benefits of Function Compositionâ
Composition offers several significant advantages:
- Modularity: Encourages the use of smaller, singleâresponsibility functions. Complex logic is broken down into simpler, more manageable pieces.
- Reusability: Functions can be combined in different ways without rewriting logic.
- Readability: Data flow is explicit â you can see exactly how data is transformed at each step.
- Avoiding Side Effects: Composition naturally encourages pure functions, reducing unintended modifications of data.
- Testability: Small functions are easier to test in isolation.
A Simple Compose Functionâ
The most basic compose function takes two functions and returns a new function that applies them in sequence.
def compose(f, g):
"""Returns a function that applies g first, then f."""
return lambda x: f(g(x))
# Define two simple functions
def add_two(x):
return x + 2
def multiply_by_three(x):
return x * 3
# Compose them
composed = compose(multiply_by_three, add_two)
# Apply the composed function
result = composed(5) # add_two(5) = 7, multiply_by_three(7) = 21
print(result) # Output: 21
The compose function takes f and g as arguments and returns a lambda that applies g(x) first, then f(g(x)). This is a pure higherâorder function â it returns a new function without side effects.
Reading Directionâ
In compose(f, g), the functions are applied from right to left: g is executed first, then f. This follows mathematical convention where (f â g)(x) = f(g(x)). Some developers find this confusing because the order of arguments appears reversed from the order of execution. For a more intuitive leftâtoâright flow, you can define a pipe function instead:
def pipe(f, g):
"""Returns a function that applies f first, then g."""
return lambda x: g(f(x))
This reads more naturally for many developers: pipe(f, g)(x) applies f(x), then g(f(x)).
Composing Multiple Functionsâ
Composing two functions is useful, but realâworld problems often involve multiple transformations. You can extend composition to handle any number of functions using functools.reduce().
from functools import reduce
def compose(*funcs):
"""Compose any number of functions from right to left."""
def compose_two(f, g):
return lambda x: f(g(x))
return reduce(compose_two, funcs, lambda x: x)
# Define three simple functions
def add_two(x):
return x + 2
def multiply_by_three(x):
return x * 3
def subtract_one(x):
return x - 1
# Compose them: subtract_one â multiply_by_three â add_two
composed = compose(subtract_one, multiply_by_three, add_two)
result = composed(5) # add_two(5) = 7, multiply_by_three(7) = 21, subtract_one(21) = 20
print(result) # Output: 20
The reduce function applies compose_two cumulatively across the list of functions. The initial value lambda x: x is the identity function, which serves as a neutral starting point.
LeftâtoâRight Composition (Pipe)â
For a more intuitive leftâtoâright flow:
def pipe(*funcs):
"""Compose any number of functions from left to right."""
def pipe_two(f, g):
return lambda x: g(f(x))
return reduce(pipe_two, funcs, lambda x: x)
pipeline = pipe(add_two, multiply_by_three, subtract_one)
result = pipeline(5) # add_two(5) = 7, multiply_by_three(7) = 21, subtract_one(21) = 20
print(result) # Output: 20
The pipe function reads naturally: data flows from left to right through each transformation.
Using functools.partial with Compositionâ
functools.partial allows you to fix arguments to a function, creating a new function with fewer parameters. This is particularly useful when composing functions that take multiple arguments.
from functools import partial
def power(base, exponent):
return base ** exponent
def add(x, y):
return x + y
# Create specialized versions using partial
square = partial(power, exponent=2)
add_three = partial(add, 3)
# Compose them
composed = compose(square, add_three)
result = composed(2) # add_three(2) = 5, square(5) = 25
print(result) # Output: 25
partial transforms a multiâargument function into a singleâargument function, making it composable.
Handling Functions with Multiple Argumentsâ
Function composition typically assumes each function takes a single argument. When you need to compose functions that accept multiple arguments, you have several options:
1. Use partial to Fix Argumentsâ
As shown above, partial can reduce a multiâargument function to a singleâargument version.
2. Use Tuples to Pass Multiple Valuesâ
You can design functions to accept and return tuples, allowing them to pass multiple values through the pipeline:
def add_coordinates(coord, dx, dy):
x, y = coord
return (x + dx, y + dy)
def scale_coordinates(coord, factor):
x, y = coord
return (x * factor, y * factor)
# Compose functions that operate on tuples
def compose_tuple(*funcs):
def compose_two(f, g):
return lambda x: f(g(x))
return reduce(compose_two, funcs, lambda x: x)
# Create partially applied versions
add_five = partial(add_coordinates, dx=5, dy=5)
scale_by_two = partial(scale_coordinates, factor=2)
composed = compose_tuple(scale_by_two, add_five)
result = composed((1, 2)) # add_five(1,2) = (6,7), scale_by_two(6,7) = (12,14)
print(result) # Output: (12, 14)
3. Use unpack for Arbitrary Argumentsâ
You can create a composition function that handles *args or **kwargs:
def compose_unpack(f, g):
def wrapper(*args, **kwargs):
return f(*g(*args, **kwargs))
return wrapper
This is more complex and should be used sparingly, as it obscures the data flow.
Practical Example: A Data Processing Pipelineâ
Function composition shines in data processing pipelines. Instead of writing a long sequence of operations with intermediate variables, you compose the operations into a single function.
from functools import reduce
def pipe(*funcs):
def pipe_two(f, g):
return lambda x: g(f(x))
return reduce(pipe_two, funcs, lambda x: x)
# Data processing functions
def clean_text(text):
return text.strip().lower()
def remove_punctuation(text):
import string
return ''.join(ch for ch in text if ch not in string.punctuation)
def split_words(text):
return text.split()
def count_words(words):
from collections import Counter
return Counter(words)
# Compose the pipeline
word_count_pipeline = pipe(
clean_text,
remove_punctuation,
split_words,
count_words
)
# Use the pipeline
text = " Hello, world! Hello, Python! "
result = word_count_pipeline(text)
print(result) # Counter({'hello': 2, 'world': 1, 'python': 1})
The pipeline reads naturally: data flows from left to right through each transformation. Each function is small, focused, and testable in isolation.
Function Composition and Decoratorsâ
Decorators are a special case of function composition. A decorator is a function that takes another function as an argument and returns a new function that wraps the original.
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with {args}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@logger
def add(a, b):
return a + b
# The decorator syntax is equivalent to:
# add = logger(add)
result = add(3, 5)
# Output: Calling add with (3, 5)
# add returned 8
Decorators compose functions by wrapping one function with another. The @ syntax is syntactic sugar for applying a higherâorder function.
Combining Multiple Decoratorsâ
When you apply multiple decorators, they compose from the inside out:
@logger
@timer
def slow_operation():
# ...
This is equivalent to logger(timer(slow_operation)). The innermost decorator is applied first, then the next one wraps the result.
Advanced Patternsâ
1. Function Composition with itertools.accumulateâ
For stepâbyâstep composition, itertools.accumulate can be used to build intermediate results:
from itertools import accumulate
def compose_step(*funcs):
"""Returns a list of all intermediate composed functions."""
def compose_two(f, g):
return lambda x: f(g(x))
return list(accumulate(funcs, compose_two))
funcs = [lambda x: x + 3, lambda x: x + 5, lambda x: x + 1]
step_functions = compose_step(*funcs)
result = [f(8) for f in step_functions]
print(result) # [11, 16, 17]
2. SelfâCompositionâ
You can compose a function with itself multiple times:
def repeat(func, times):
"""Returns a function that applies func 'times' times."""
def compose_two(f, g):
return lambda x: f(g(x))
return reduce(compose_two, [func] * times, lambda x: x)
increment = lambda x: x + 1
add_five = repeat(increment, 5)
print(add_five(10)) # 15
3. Composition with Side Effectsâ
Pure functions are the ideal for composition, but you can also compose functions with controlled side effects using functools.partial or custom wrappers.
Common Mistakes and How to Avoid Themâ
1. Confusing Argument Orderâ
In compose(f, g), the functions are applied from right to left. This is the mathematical convention, but it can be confusing. If you prefer leftâtoâright, use pipe instead.
2. Forgetting the Identity Functionâ
When composing multiple functions with reduce, always use lambda x: x as the initial value. This identity function ensures that composition works correctly when no functions are provided.
3. Composing Functions with Different Aritiesâ
Function composition typically assumes each function takes a single argument. If your functions take multiple arguments, use functools.partial to reduce them to singleâargument functions, or use tuples to pass multiple values through the pipeline.
4. Mutating State Inside Composed Functionsâ
Composition works best with pure functions â functions that have no side effects. If a composed function mutates external state, the composition becomes impure and harder to reason about.
Summaryâ
Function composition is a fundamental concept in functional programming that allows you to combine simple functions into more complex operations. Python supports composition through higherâorder functions, functools.reduce, and the functools.partial utility. By composing functions, you write code that is more modular, reusable, and readable. You build complex logic from small, focused building blocks that are easy to test and maintain.
The key to effective composition is to write pure functions that take a single argument or can be reduced to a single argument using partial. From there, you can combine them into pipelines that express data flow clearly and declaratively. Whether you are processing data, building APIs, or orchestrating complex transformations, function composition is a tool that belongs in every Python developer's toolkit.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Higher-Order Functions
Next
Closures
-
What Is Function Composition?
- Mathematical Notation
- Benefits of Function Composition
-
A Simple Compose Function
- Reading Direction
-
Composing Multiple Functions
- LeftâtoâRight Composition (Pipe)
-
Using
functools.partialwith Composition -
Handling Functions with Multiple Arguments
- 1. Use
partialto Fix Arguments - 2. Use Tuples to Pass Multiple Values
- 3. Use
unpackfor Arbitrary Arguments
- 1. Use
-
Practical Example: A Data Processing Pipeline
-
Function Composition and Decorators
- Combining Multiple Decorators
-
Advanced Patterns
- 1. Function Composition with
itertools.accumulate - 2. SelfâComposition
- 3. Composition with Side Effects
- 1. Function Composition with
-
Common Mistakes and How to Avoid Them
- 1. Confusing Argument Order
- 2. Forgetting the Identity Function
- 3. Composing Functions with Different Arities
- 4. Mutating State Inside Composed Functions
-
Summary
