一尘不染

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

python

给这个字典:

>>> options = {'DATABASES': {'default': {'ENGINE': 'django.db.backends.sqlite3'}}}

最好的方法是什么?

>>> foo(options)
>>> print DATABASES
{'default': {'ENGINE': 'django.db.backends.sqlite3'}}

我正在解决这是locals()。update(options),但我在想,是否有更好的解决方案。


阅读 166

收藏
2021-01-20

共1个答案

一尘不染

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

例:

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

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
 ...

和其他正常的“ from .... import ....”用法,但来自字典或映射对象(包括默认字典)。

2021-01-20