Python: load variables in a dict into namespace

好久不见. 提交于 2019-11-26 21:53:39

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

You can import variables in one local namespace into another local namespace. For example, you can do:

adict = { 'x' : 'I am x', 'y' : ' I am y' }
locals().update(adict)
blah(x)
blah(y)

Although and you need to be careful not to pollute the common global namespace and the documentation for locals() states

Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

Rather than create your own object, you can use argparse.Namespace:

from argparse import Namespace
ns = Namespace(**mydict)

To do the inverse:

mydict = vars(ns)

Importing variables into a local namespace is a valid problem and often utilized in templating frameworks.

Return all local variables from a function:

return locals()

Then import as follows:

r = fce()
for key in r.keys():
   exec(key + " = r['" + key + "']")

There's Always this option, I don't know that it is the best method out there, but it sure does work. Assuming type(x) = dict

for key, val in x.items():  # unpack the keys from the dictionary to individual variables
    exec (key + '=val')

Used following snippet (PY2) to make recursive namespace from my dict(yaml) configs:

class NameSpace(object):
    def __setattr__(self, key, value):
        raise AttributeError('Please don\'t modify config dict')


def dump_to_namespace(ns, d):
    for k, v in d.iteritems():
        if isinstance(v, dict):
            leaf_ns = NameSpace()
            ns.__dict__[k] = leaf_ns
            dump_to_namespace(leaf_ns, v)
        else:
            ns.__dict__[k] = v

config = NameSpace()
dump_to_namespace(config, config_dict)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!