简体   繁体   中英

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.

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

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

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM