Python: load variables in a dict into namespace

前端 未结 7 740
天命终不由人
天命终不由人 2020-11-27 12:15

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

7条回答
  •  温柔的废话
    2020-11-27 12:49

    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)
    

提交回复
热议问题