"拆包"一个传递的字典到Python中的函数的名字空间? [英] "unpacking" a passed dictionary into the function's name space in Python?
问题描述
在我做的工作中,为了方便起见,我经常有参数需要分组到子集中:
In the work I do, I often have parameters that I need to group into subsets for convenience:
d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}
我通过传递多个字典来做到这一点。大多数时候我直接使用传递的字典,即:
I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:
def f(d1,d2):
for k in d1:
blah( d1[k] )
在某些功能中,我需要直接访问变量,事情变得麻烦了;我真的希望这些变量在本地名称空间。我想要这样做:
In some functions I need to access the variables directly, and things become cumbersome; I really want those variables in the local name space. I want to be able to do something like:
def f(d1,d2)
locals().update(d1)
blah(x)
blah(y)
locals()返回的字典的更新不能保证实际更新命名空间。
but the updates to the dictionary that locals() returns aren't guaranteed to actually update the namespace.
这是明显的手动方式:
def f(d1,d2):
x,y,a,b = d1['x'],d1['y'],d2['a'],d2['b']
blah(x)
return {'x':x,'y':y}, {'a':a,'b':b}
这将导致每个功能的参数列表重复三次。这可以通过装饰器自动进行:
This results in three repetitions of the parameter list per function. This can be automated with a decorator:
def unpack_and_repack(f):
def f_new(d1, d2):
x,y,a,b = f(d1['x'],d1['y'],d2['a'],d3['b'])
return {'x':x,'y':y}, {'a':a,'b':b}
return f_new
@unpack
def f(x,y,a,b):
blah(x)
blah(y)
return x,y,a,b
这样做会导致装饰器重复三次,每个功能加上两个重复,所以如果你有很多功能,它会更好。
This results in three repetitions for the decorator, plus two per function, so it's better if you have a lot of functions.
是否有一个更好的方法?也许有什么使用eval?谢谢!
Is there a better way? Maybe something using eval? Thanks!
推荐答案
您可以随时将一个字典作为参数传递给函数。例如,
You can always pass a dictionary as an argument to a function. For instance,
dict = {'a':1, 'b':2}
def myFunc(a=0, b=0, c=0):
print(a,b,c)
myFunc(**dict)
这篇关于"拆包"一个传递的字典到Python中的函数的名字空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!