Currying Function in Python and its advantages
In this tutorial, we are gonna learn what is currying function in Python, its advantages and learn where we can use it.
Currying function in Python
What is Currying?
How it works
Let’s take the below example to explain the concept.
f(a,b,c) -> f(a)(b)(c)
Here f(a,b,c) is a function which takes 3 arguments a,b and c simultaneously and computes the result but after currying we get f(a)(b)(c) where f is a function which takes ‘a’ as its first argument here ‘a’ return another function which takes second argument ‘b’ and returns another function which takes the third argument. so we go from a function with 3 arguments to a chain of functions which each takes an argument.
Now, let’s take a look at a practical example for more understanding (let’s take the example of addition function) :
Example of Currying function in Python
def add(a,b,c): return a+b+c print(add(1,2,3))
output : 6
This is a simple example of a function adding 3 numbers, the same code in currying can be written as below
def add(a): def w(b): def x(c): print(a+b+c) return x return w add(1)(2)(3)
here add is the main function and w, x are the chain of functions and we can see that each function is taking only one argument and we say add is a curried function.
- It helps in reusing the code and makes the life of coder a little easier.
- Little pieces can be configured and reused with ease, without clutter.
- Functions are used throughout.
- It offers a cheap form of dependency injection
- It’s an easy way to get specialized functions from more general functions
You may also read