Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - enter the correct number of variables based on function handle

Tags:

python

I have a list of variables, and a function object and I would like to assign the correct number of variable depending on the function.

def sum2(x,y):
    return x + y

def sum3(x,y,z):
    return x + y + z

varList = [1,2,3]

so if f = sum2 , I would like it to call first 2 elements of varList, and if f = sum3 , to call it with 3 elements of the function.

like image 792
javish Avatar asked Jun 02 '15 13:06

javish


4 Answers

This can be done in a single function, if you are always returning the sum of all the passed arguments.

def sum1(*args):
    return sum(args)

This is just utilizing positional arguments, as you don't appear to need to explicitly set individual values. It is also most flexible than the solution provided by ZdaR, as you don't need to know ahead of time the maximum number of arguments you can receive.

Some examples:

>>> print sum1(1, 2, 3)
6
>>> print sum1(1)
1
>>> print sum1(-1, 0, 6, 10)
15
like image 170
Andy Avatar answered Oct 12 '22 17:10

Andy


Use the inspect module as follows:

import inspect
n2 = len(inspect.getargspec(sum2)[0])
n3 = len(inspect.getargspec(sum3)[0])
sum2(*varList[0:n2])
sum3(*varList[0:n3])

getargspec returns a 4-tuple of (args, varargs, keywords, defaults). So the above code works if all your args are explicit, i.e. not * or ** args. If you have some of those, change the code accordingly.

like image 23
Synergist Avatar answered Oct 12 '22 18:10

Synergist


You may use default initialization, You should keep in mind the maximum number of variables that could be passed to this function. Then create a function with that number of parameters but initializing them with 0, because a+0 = a(in case some parameters are missing it will replace then with 0 which won't affect the results.)

def sum1(a=0, b=0, c=0, d=0):
    return a+b+c+d

print sum1(1)
>>> 1

print sum1(1, 2)
>>> 3

print sum1(1, 2, 3)
>>> 6

print sum1(1, 2, 3, 4)
>>> 10

However, if you call the function with more than 4 arguments, it would raise error statement

Also as suggested by @CoryKramer in the comments you can also pass your varlist = [1, 2, 3, 4] as a parameter :

print sum1(*varlist)
>>> 10

Keeping in mind that the len(varlist) should be less than the number of parameters defined.

like image 22
ZdaR Avatar answered Oct 12 '22 17:10

ZdaR


A general solution:

To get the number of argument, you can use f.func_code.co_argcount and than pass the correct elements from the list:

def sum2(x,y):
    return x + y

def sum3(x,y,z):
    return x + y + z

varlist = [2,5,4]


[f(*varlist[:f.func_code.co_argcount]) for f in [sum2,sum3]]

>> [7, 11]
like image 25
farhawa Avatar answered Oct 12 '22 16:10

farhawa