Python:将字典中的变量加载到名称空间中 [英] Python: load variables in a dict into namespace
问题描述
我想在函数外部使用一堆在函数中定义的局部变量.因此,我在返回值中传递了x=locals()
.
I want to use a bunch of local variables defined in a function, outside of the function. So I am passing x=locals()
in the return value.
如何将该词典中定义的所有变量加载到函数外部的名称空间中,这样我可以简单地使用variable
,而不是使用x['variable']
访问值.
How can I load all the variables defined in that dictionary into the namespace outside the function, so that instead of accessing the value using x['variable']
, I could simply use variable
.
推荐答案
考虑Bunch
替代方法:
class Bunch(object):
def __init__(self, adict):
self.__dict__.update(adict)
因此,如果您有字典d
,并且想要使用语法x.foo
而不是笨拙的d['foo']
访问(读取)其值,则只需
so if you have a dictionary d
and want to access (read) its values with the syntax x.foo
instead of the clumsier d['foo']
, just do
x = Bunch(d)
这在内部和外部函数中均有效-与将d
注入globals()
相比,它非常更干净,更安全!记住Python Zen中的最后一行...:
this works both inside and outside functions -- and it's enormously cleaner and safer than injecting d
into globals()
! Remember the last line from the Zen of Python...:
>>> import this
The Zen of Python, by Tim Peters
...
Namespaces are one honking great idea -- let's do more of those!
这篇关于Python:将字典中的变量加载到名称空间中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!