“开箱"在 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
这导致装饰器重复 3 次,每个函数重复两次,所以如果你有很多函数,效果会更好.
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屋!