Shoaib Akhtar Shoaib Akhtar - 1 year ago 74
Python Question

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

I am calculating a sum using

like this:

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


and it's output is

But I want a
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
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 Source

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)


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download