如何将dict中的所有键作为局部变量加载,这是一个更好的方法?

Mar*_*sar 7 python

给这本词典:

>>> options = {'DATABASES': {'default': {'ENGINE': 'django.db.backends.sqlite3'}}}
Run Code Online (Sandbox Code Playgroud)

得到这个最好的方法是什么?:

>>> foo(options)
>>> print DATABASES
{'default': {'ENGINE': 'django.db.backends.sqlite3'}}
Run Code Online (Sandbox Code Playgroud)

我解决这个问题是本地人().更新(选项),但我在想,如果有更好的解决方案.

jsb*_*eno 8

import inspect

allowed_vars = set(["min_", "max_", "path", ...])
def update_globals(dic):
    caller_frame = inspect.currentframe(1)
    globals = caller_frame.f_globals
    # here, you _could_ simply do globals.update(dic) 
    # but it is  evil
    for key, value in dic.items():
        #here you should carefully verify each key, and value for not
        #not dangerous pairs, with stuff like:
        #if key not in allowed_vars:
        #    sys.stderr.write("Warning: invalid variable in configuration update\n")
        #     continue
        #if type(value) not in (string, int, float):
        #    #(issue error)
        #    continue
        globals[key] = value
Run Code Online (Sandbox Code Playgroud)

例:

>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> update_globals({"a": 5})
>>> a
5
Run Code Online (Sandbox Code Playgroud)

更新2016-06几周前我把extradictPython包放在一起- 现在可以在pypi上找到它.它的一个功能是MapGetter上下文管理器,它可以通过执行某些操作来准确地提出要求:

from extradict import MapGetter

def myfunc():
    options = {'DATABASES': {'default': {'ENGINE': 'django.db.backends.sqlite3'}}}
    with MapGetter(options) as options:
         from options import DATABASES
 ...
Run Code Online (Sandbox Code Playgroud)

和其他正常的"从......导入...."使用,但来自字典或映射对象(包括默认字典).