【发布时间】:2019-03-01 11:30:01
【问题描述】:
给定一个堆栈帧和一个变量名,我如何判断该变量是否是非本地的?示例:
import inspect
def is_nonlocal(frame, varname):
# How do I implement this?
return varname not in frame.f_locals # This does NOT work
def f():
x = 1
def g():
nonlocal x
x += 1
assert is_nonlocal(inspect.currentframe(), 'x')
g()
assert not is_nonlocal(inspect.currentframe(), 'x')
f()
【问题讨论】:
-
如果是非本地,
varname应该在frame.f_locals吗? -
@WillemVanOnsem:我有一个错字,我在一两分钟内修正了它。
-
@Jean-FrançoisFabre:相关,但不是重复的。但是,那里的答案似乎非常,非常错误!
f_back给出调用者的框架(动态范围),而不是定义者的框架(词法范围)!!! -
请注意我没有关闭问题:)
标签: python python-3.x stack-frame python-nonlocal