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

发布于 2021-01-29 14:57:18

给这个字典:

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

最好的方法是什么?

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

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

关注者
0
被浏览
70
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。
    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 ....”用法,但来自字典或映射对象(包括默认字典)。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看