python - enter the correct number of variables based on function handle -
i have list of variables, , function object , assign correct number of variable depending on 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 , call first 2 elements of varlist, , if f = sum3 , call 3 elements of function.
use inspect
module 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 4-tuple of (args, varargs, keywords, defaults)
. above code works if args explicit, i.e. not * or ** args. if have of those, change code accordingly.
Comments
Post a Comment