如果我在Python中评估一些东西:
eval("a + b")
Run Code Online (Sandbox Code Playgroud)
这将使用当前范围(本地和全局)来评估表达式.
我正在开发的内容要求"稍后"评估表达式.这个词意味着我想保持当前的范围(即locals()和globals()).但是我希望透明地传递这些值......或者从上层栈帧中获取它们.考虑这个实现(实际上,这个实现):
def __eval(self, expr):
if isinstance(expr, (list, tuple, set, frozenset, dict, Expression)):
return Expression.eval(expr, self)
elif callable(expr):
try:
return expr(self)
except (AttributeError, IndexError, KeyError, TypeError):
return UNDEFINED
else:
try:
return eval(expr, {}, {'self': self})
except (AttributeError, IndexError, KeyError, TypeError):
return UNDEFINED
Run Code Online (Sandbox Code Playgroud)
该实现解释如下:
locals()和来执行这样的评估globals().我知道我可以明确地打电话:
o._O__eval("self.a + self.b", globals(), locals())
#THIS WOULD REQUIRE to alter the method to allow two additional dict parameters
#NO, I will not call this function directly, but lets follow the example
Run Code Online (Sandbox Code Playgroud)
但我希望得到这样的globals(),locals没有用户明确地传递它并在中使用这些值eval.
问:是否有可能得到locals()和globals()从上部栈帧?
你应该考虑只是传入 globals()和locals():
def __eval(self, expr, eval_globals=None, eval_locals=None):
if eval_globals is None:
eval_globals = globals()
if eval_locals is None:
eval_locals = eval_globals()
Run Code Online (Sandbox Code Playgroud)
如果这不是您的选项,您可以使用该sys._getframe()函数访问父框架,并且locals和globals是该框架上的属性:
def __eval(self, expr, eval_globals=None, eval_locals=None):
call_frame = sys._getframe(1)
eval_globals, eval_locals = call_frame.f_globals, call_frame.f_locals
Run Code Online (Sandbox Code Playgroud)