似乎不能将带有非字符串关键字的dicts传递给Python中的函数。(我看这是在here之前提出来的)
然而,在为我的问题想出一些复杂的解决方案之前,我想我应该问问专家,看看是否有我遗漏的东西。不幸的是,如果没有重要的重构,我就不能轻易地改变这个范式,因为前面的作者从来没有预料到这种动作(这是一个非常简单的例子)。
我有一个名为services的对象,可以在nodes上执行操作。有些nodes需要不同的service配置。而不是每个node有一个node实例,而是每个service的一个实例,然后将其与每个node的配置参数组合起来。service及其相应的配置参数存储在dict中。
node及其services及其相应的配置参数都传递给一个函数(setupServices),该函数随后处理所有内容。该函数必须能够调用作为service对象一部分的函数。不幸的是,这个错误失败了:
TypeError: setupServices() keywords must be strings如果您想知道是什么将它作为**nodeServices传递,而不仅仅是nodeServices,那么它就是下面的代码段(在本例中,值是nodeServices )。我不太愿意让这段代码特定于个别情况,因为它充当了许多其他事情的骨干。
if type( value ) is list:
result = f( *value )
elif type( value ) is dict:
result = f( **value )
else:
result = f( value )
results[ name ] = result
return result还有其他方法可以用最小的修改来完成这个任务吗?
"A node can be associated with many services"
class Node(object):
pass
"""Setup services routine (outside of the node due to an existing design choice)
I could rewrite, but this would go against the existing author's paradigms"""
def setupServices ( node, **nodeServices ):
for object, objOverrides in nodeServices.items():
"do something with the service object"
"2 simple services that can be perform actions on nodes"
class serviceA(object):
pass
class serviceB(object):
pass
"instantiate an object of each service"
a = serviceA()
b = serviceB()
"Create a node, assign it two services with override flags"
node = Node()
nodeServices = {}
nodeServices[a] = { 'opt1' : True }
nodeServices[b] = { 'opt2' : False }
"Pass the node, and the node's services for setup"
setupServices ( node, **nodeServices )发布于 2014-04-20 21:22:14
更改的最简单方法是更改setupServices,使其不再接受关键字参数,而只接受一些选项。也就是说,将其定义改为:
def setupServices (node, nodeServices):(删除**)。然后,您可以使用setupServices(node, nodeServices)调用它。
唯一的缺点是,您必须传递一个dict,并且不能传递文字关键字参数。使用关键字参数设置,您可以调用setupServices(node, opt1=True),但不需要关键字参数,如果您想要指定“内联”选项,就必须执行setupServices(node, {'opt1': True}),传入一个文字字典。但是,如果您总是以编程的方式创建一个选项块,然后将其传递给**,那么这个缺点并不重要。只有当您实际拥有传递文字关键字参数(如setupServices(node, foo=bar) )的代码时,这才是重要的。
正如您所链接的问题中的答案所述,没有办法使函数接受非字符串关键字参数。因此,当foo(**nodeServices)的键不是字符串时,您就无法让nodeServices工作。(考虑到这一点,很难理解这个方案是如何工作的,因为在您的示例中,似乎setupServices总是期望一个键是服务对象的dict,这意味着将它们作为关键字参数传递永远不会奏效。)
https://stackoverflow.com/questions/23187665
复制相似问题