Search⌘ K
AI Features

Creating a Compose Function

Explore how to create and extend compose functions in Python that combine multiple functions into a single operation. Understand the use of closures and the reduce function to handle lists of functions, enabling efficient function composition in functional programming.

How to create a compose function

The composition examples in the previous lesson are quite procedural – we are composing functions by writing code that calls one function and then calls another function using the result from the first call.

One example is given below to refresh your memory.

Python 3.8
from functools import partial
from operator import add, mul
f = partial(add, 2)
g = partial(mul, 3)
x = 1
print(f(g(x)))

We are writing code that describes how to do the composition rather than simply declaring that we want the composition to happen.

In the earlier chapter on closures, we created this simple compose function that accepted two functions and returned a function that composed them:

def compose2(f, g):
   def fn(x):
      return f(g(x))
   return fn

Here we have renamed this function to compose2. compose2 is a function that ...