Rich
Rich

Reputation: 12663

How to construct dynamic function invocation with variable arguments in Python

I'm attempting to wrap a call to an operation with a variable argument list into a generalized function with fixed arguments like this:

def vectorizeIt(args, op)

op is a function with a variable number of arguments and args is a list with the arguments I'd like to pass to it. For example if len(args) == 3 then I'd like to call op like this: op(args[0],args[1],args[2]). As far as I can tell, op needs to have the arguments explicitly passed like that; I can't change the argument list to just be a single list or dictionary. Any suggestions about how to do this are appreciated.

Upvotes: 2

Views: 532

Answers (1)

unutbu
unutbu

Reputation: 879899

Use the "splat" operator * to apply an arbitrary number of arguments to op:

def vectorizeIt(args, op):
    op(*args)

Reference:

Upvotes: 4

Related Questions