【发布时间】:2020-07-02 16:04:42
【问题描述】:
我有一个自定义函数,该函数接受一堆参数,并使用所述参数的不同配置多次调用。为了清洁和易用,我想在所有函数调用之前定义一个参数字典,然后将其作为**kwargs传递给每个调用:
def func(arg1, arg2, arg3, opt_arg4=x, opt_arg5=y, opt_arg6=z):
do_something
dict1 = {'arg1': 'foo', 'arg2': 'bar', 'arg3': 'baz', 'opt_arg4': 42}
dict2 = {'arg1': 'Ni', 'arg2': 'Peng', 'arg3': 'Neee-Wom', 'opt_arg5': 'yellow'}
dict3 = {'arg1': 'Ni', 'arg2': 'bar', 'arg3': 'Ekke ekke', 'opt_arg6': name}
func(**dict1)
func(**dict2)
func(**dict3)
如果我希望字典中的某些参数是尚未定义的变量,就会出现我的问题。因此,它们将在分配之前被引用,除了在实际使用之前稍后定义的占位符。例如,上面的dict3 包含'opt_arg6': name,其中name 是一个变量,它可以这样使用:
knightlist = ['Lancelot', 'Galahad', 'Robin']
for name in knightlist:
func(**dict3)
有没有办法做到这一点或达到类似的结果?
编辑: 稍微详细一点,摘自实际代码:
i = 1
for c in c_list: # Where c_list has been read in from input
compile_func(somedict[c], c, i, {'model': f'_{c}', 'optparm': '_i'}, log=logfile, subdir=c)
# Where somedict and logfile have previously been defined
我希望能够将其替换为:
c_args = {'arg1': somedict[c], 'arg2': c, 'arg3': i, 'arg4': {'model': f'_{c}', 'optparm': '_i'}, 'log': logfile, 'subdir': c}
# With the actual arg names as keys of course
Bunch_of_other_code()
i=1
for c in c_list:
compile_func(**c_args)
或类似的可分离的东西。希望这更清楚!
编辑 2: 试图解决更根本的问题: 对于一个有很多参数的函数,其中一些是变量或变量的修改,有什么方法可以传递相对整洁、可读和容易修改的参数?特别是如果使用不同的参数集多次调用,我希望能够在代码中的同一位置进行配置?
【问题讨论】:
-
有什么问题:
dict3['opt_arg6'] = name就在func(**dict3)之前? -
@stovfl 请参阅下面的编辑和讨论 - 实际代码涉及更多变量或对其进行修改,因此虽然这会起作用,但它会变得非常混乱,这会破坏我在第一名(比在每个函数调用中输入所有参数更整齐地组织它)。
标签: python python-3.x function