Currying in Python Using functools.partial

PythonPythonBeginner
Practice Now

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

Introduction

In functional programming, currying is a technique of transforming a function that takes multiple arguments into a sequence of functions that each take a single argument. In Python, we can use the functools.partial() function to implement currying.


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-13611{{"`Currying in Python Using functools.partial`"}} python/keyword_arguments -.-> lab-13611{{"`Currying in Python Using functools.partial`"}} python/tuples -.-> lab-13611{{"`Currying in Python Using functools.partial`"}} python/function_definition -.-> lab-13611{{"`Currying in Python Using functools.partial`"}} python/lambda_functions -.-> lab-13611{{"`Currying in Python Using functools.partial`"}} python/importing_modules -.-> lab-13611{{"`Currying in Python Using functools.partial`"}} python/using_packages -.-> lab-13611{{"`Currying in Python Using functools.partial`"}} python/standard_libraries -.-> lab-13611{{"`Currying in Python Using functools.partial`"}} end

Curry Function

Write a function curry(fn, *args) that curries a given function fn. The function should return a new function that behaves like fn with the given arguments, args, partially applied.

from functools import partial

def curry(fn, *args):
  return partial(fn, *args)
add = lambda x, y: x + y
add10 = curry(add, 10)
add10(20) ## 30

Summary

In this challenge, you learned how to implement a curry function using functools.partial() in Python. The curry function allows you to partially apply arguments to a function and return a new function that takes the remaining arguments.

Other Python Tutorials you may like