简体   繁体   中英

Python function call, how to pass in multiple function parameters as a single variable string?

I have a Python function that takes one required parameter and four optional ones. If an optional param has no value it needs to be omitted from the call to the function. An example call will be like the following with all params specified.

MyFunction(required='Delta', param1='ABC', param2='XYZ', ID=1234, title='Imp Info') 

I would like to gather all of my optional params into a variable and then pass a variable into the function. This will make handling the optional params easier. Something like the following:

myVar = "param2='XYZ', ID=1234, title='Imp Info'"
MyFunction(param1='Delta', myVar) 

I've tried the above but it failed with a syntax error. How can I pass function params as a variable? I appreciate any guidance.

Don't pass them in as a string; pass them in as an unpacked dictionary:

myVar = {'param2':'XYZ', 'ID':1234, 'title':'Imp Info'}
MyFunction(param1='Delta', **myVar)

The ** will unpack the dictionary and send each element as a named argument.

您可以使用MyFunction(parameters, *args, **kwargs) ,也可以定义一个方法,该方法按空格分割字符串,然后解析或使用eval (不推荐)来分配变量。

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