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 A数週間前に私はextradict
Pythonパッケージをまとめました。それはpypi nowで利用できます。その機能の1つはコンテキストマネージャです。これは何かを実行して の質問を正確に行うことができます:
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 ...."の使用法ではなく、辞書またはマッピングオブジェクト(デフォルトのdictを含む)からのものです。
最良の方法は、まず第一に、このような危険なことを行うことではありません。そして、幸いなことに、関数だけでは現在の名前空間で欺くことができません(実際には、グローバルなものと、おそらくもっと悪い反射のハッカーを使用しているかもしれませんが、考えてみてください)。 – delnan
@デルナン私は地元の人()が醜い使用を理解しています。設定ファイルを解析した後、オプション辞書を取得するので、どのように設定のデフォルト値の値をlocals()を使用して置き換えることができますか?¿ –
あなたはうまくいけません。なぜなら、そうすることは変数を変数 '' eval'の上の1ステップだけであるユーザ入力で上書きすることを意味するからです。辞書に入ってください。 – delnan