Function Composition with Python

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Function composition is a technique used in functional programming to combine two or more functions to form a new function. In Python, we can use the functools.reduce() function to perform right-to-left function composition.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FunctionsGroup -.-> python/keyword_arguments("`Keyword Arguments`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") subgraph Lab Skills python/comments -.-> lab-13607{{"`Function Composition with Python`"}} python/keyword_arguments -.-> lab-13607{{"`Function Composition with Python`"}} python/tuples -.-> lab-13607{{"`Function Composition with Python`"}} python/function_definition -.-> lab-13607{{"`Function Composition with Python`"}} python/lambda_functions -.-> lab-13607{{"`Function Composition with Python`"}} python/importing_modules -.-> lab-13607{{"`Function Composition with Python`"}} python/using_packages -.-> lab-13607{{"`Function Composition with Python`"}} python/standard_libraries -.-> lab-13607{{"`Function Composition with Python`"}} end

Compose Functions

Write a function called compose(*fns) that accepts one or more functions as arguments and returns a new function that is the result of composing the input functions from right to left. The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.

from functools import reduce

def compose(*fns):
  return reduce(lambda f, g: lambda *args: f(g(*args)), fns)
add5 = lambda x: x + 5
multiply = lambda x, y: x * y
multiply_and_add_5 = compose(add5, multiply)
multiply_and_add_5(5, 2) ## 15

Summary

In this challenge, you learned how to use the functools.reduce() function to perform right-to-left function composition in Python. You also wrote a function called compose() that accepts one or more functions as arguments and returns a new function that is the result of composing the input functions from right to left.

Other Python Tutorials you may like