在不破坏字典的情况下将 eval 与字典值一起使用?
Use of eval with dictionary values without breaking dictionary?
我正在尝试将 eval
与字典中的变量一起使用,因此设置非常简单:
d = {"x": 0}
e = "x**2"
v = eval(e, d)
但是,出于某种原因,这会通过添加额外的键来破坏字典,使其变得毫无用处:
print(d)
>>> {'x': 0, '__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", (...)
这是 eval
的 "expected" 行为,但这看起来几乎像是一个错误。那么,在不破坏字典的情况下,将字典 key/values 与 eval
一起使用的最 pythonic 方式是什么?
我不容忍使用 eval
,但是...
如果你不希望d
发生变异,传入一份副本如何?
>>> d = {"x": 0}
>>> e = "x**2"
>>> v = eval(e, d.copy())
>>> d
{'x': 0}
eval
似乎只修改参数传递以用作全局变量,而不是局部变量。
>>> eval(e, None, d)
0
>>> d
{'x': 0}
来自文档:
If the globals dictionary is present and lacks __builtins__
, the current globals are copied into globals before expression is parsed.
我正在尝试将 eval
与字典中的变量一起使用,因此设置非常简单:
d = {"x": 0}
e = "x**2"
v = eval(e, d)
但是,出于某种原因,这会通过添加额外的键来破坏字典,使其变得毫无用处:
print(d)
>>> {'x': 0, '__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", (...)
这是 eval
的 "expected" 行为,但这看起来几乎像是一个错误。那么,在不破坏字典的情况下,将字典 key/values 与 eval
一起使用的最 pythonic 方式是什么?
我不容忍使用 eval
,但是...
如果你不希望d
发生变异,传入一份副本如何?
>>> d = {"x": 0}
>>> e = "x**2"
>>> v = eval(e, d.copy())
>>> d
{'x': 0}
eval
似乎只修改参数传递以用作全局变量,而不是局部变量。
>>> eval(e, None, d)
0
>>> d
{'x': 0}
来自文档:
If the globals dictionary is present and lacks
__builtins__
, the current globals are copied into globals before expression is parsed.