Python:将字典中的变量加载到命名空间中 [英] Python: load variables in a dict into namespace

查看:32
本文介绍了Python:将字典中的变量加载到命名空间中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在函数之外使用一堆定义在函数中的局部变量.所以我在返回值中传递 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 之禅的最后一行...:

<预><代码>>>>导入这个Python 之禅,作者:Tim Peters...命名空间是一个很棒的主意——让我们做更多的事情!

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆