On this page

Function Composition in Python: A Functional Programming Guide

Published on July 6, 2026

Enrico Hochkoeppler Profile

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:


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!

Buy Me a Coffee

Previous

Higher-Order Functions

Next

Closures