Python:将字典中的变量加载到命名空间中 [英] Python: load variables in a dict into namespace
问题描述
我想在函数之外使用一堆定义在函数中的局部变量.所以我在返回值中传递 x=locals()
.
如何将字典中定义的所有变量加载到函数外部的命名空间中,以便我可以简单地使用 而不是使用
.x['variable']
访问值变量
考虑 Bunch
替代方案:
class Bunch(object):def __init__(self, adict):self.__dict__.update(adict)
所以如果你有一个字典 d
并且想要使用语法 x.foo
而不是笨拙的 d['foo> 来访问(读取)它的值']
,就做
x = Bunch(d)
这在函数内部和外部都有效——而且它比将 d
注入到 globals()
中非常更干净、更安全!记住 Python 之禅的最后一行...:
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.
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
.
Consider the Bunch
alternative:
class Bunch(object):
def __init__(self, adict):
self.__dict__.update(adict)
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)
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屋!