给定一个堆栈帧和一个变量名,我如何判断该变量是否是非本地的?例子:
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()