Currying is a technique in mathematics and computer science named after the mathematician Haskell Curry.
In simple terms, you create new functions from a function that takes multiple arguments, each derived function will then take only a single argument.
This is done by applying Partial Argument Application to the function with multiple arguments that you are deriving.
Code Example
Let’s visualize this with a simple function that multiplies two numbers:
def multiply_numbers(a, b):
return a * bUsing this function as a base, we decided to create a new function that takes a single argument and always multiplies the argument by 3, so the second function below calls the first one above but keeping the first argument of multiply_numbers(a, b) fixed as 3.
def multiply_by_three(a):
return multiply_numbers(a, 3)Rewriting multiply_by_three(a) as a lambda function, the code above will turn into:
multiply_by_three = lambda a : multiply_numbers(a, 3)The argument b from multiply_numbers(a, b) was curried.
The partial function
The functools built-in module has the partial() function that allows us to use a partial application of a function in a more simplified way:
from functools import partial
multiply_by_three = partial(multiply_numbers, 3)Executing the function multiply_by_three above with 5 as argument, we have:
>>> multiply_by_three(5)
15