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?

Just imagine we have a function to which we are passing multiple arguments, for example, add(10,20,30), here we are passing 3 arguments to add function. Now if we can somehow convert this function such that it takes only one argument at a time in a series of function but performs the same operation as the original function then it is called a currying function.

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)

output: 6

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.

Why Currying?

  • 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

Leave a Reply

Your email address will not be published. Required fields are marked *