Shoaib Akhtar Shoaib Akhtar - 3 months ago 10
Python Question

Can lambda work with *args as it's parameter?

I am calculating a sum using

lambda
like this:

def my_func(*args):
return reduce((lambda x, y: x + y), args)

my_func(1,2,3,4)


and it's output is
10
.

But I want a
lambda
function that takes random arguments and sums all of them. Suppose this is a lambda function:

add = lambda *args://code for adding all of args


someone should be able to call the
add
function as:

add(5)(10) # it should output 15
add(1)(15)(20)(4) # it should output 40


That is, one should be able to supply arbitrary
number of parenthesis.

is this possible in Python?

Answer

This is not possible with lambda, but it is definitely possible to do this is Python.

To achieve this behaviour you can subclass int and override its __call__ method to return a new instance of the same class with updated value each time:

class Add(int):
    def __call__(self, val):
        return type(self)(self + val)

Demo:

>>> Add(5)(10)
15
>>> Add(5)(10)(15)
30
>>> Add(5)
5
# Can be used to perform other arithmetic operations as well
>>> Add(5)(10)(15) * 100
3000

If you want to support floats as well then subclass from float instead of int.