如何检查具有给定名称的变量是否为非本地变量? [英] How to check if a variable with a given name is nonlocal?
问题描述
给出一个堆栈框架和一个变量名,如何判断该变量是否为非本地变量?示例:
Given a stack frame and a variable name, how do I tell if that variable is nonlocal? Example:
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()
推荐答案
检查框架的代码对象的co_freevars
,它是代码对象使用的闭包变量名称的元组:
Check the frame's code object's co_freevars
, which is a tuple of the names of closure variables the code object uses:
def is_nonlocal(frame, varname):
return varname in frame.f_code.co_freevars
请注意,这是闭包变量,即nonlocal
语句查找的变量的类型.如果要包括所有非局部变量,则应检查co_varnames
(内部作用域中未使用的局部变量)和co_cellvars
(内部作用域中使用的局部变量):
Note that this is specifically closure variables, the kind of variables that the nonlocal
statement looks for. If you want to include all variables that aren't local, you should check against co_varnames
(local variables not used in inner scopes) and co_cellvars
(local variables used in inner scopes):
def isnt_local(frame, varname):
return varname not in (frame.f_code.co_varnames + frame.f_code.co_cellvars)
此外,请不要将其与当前错误记录的co_names
混淆. inspect
文档说co_names
是用于局部变量的,但是co_names
是某种其他"的容器.它包括全局名称,属性名称和导入中涉及的几种名称-大多数情况下,如果预计执行实际上需要名称的字符串形式,则将其放在co_names
中.
Also, don't mix things up with co_names
, which is currently misdocumented. The inspect
docs say co_names
is for local variables, but co_names
is kind of an "everything else" bin. It includes global names, attribute names, and several kinds of names involved in imports - mostly, if execution is expected to actually need the string form of the name, it goes in co_names
.
这篇关于如何检查具有给定名称的变量是否为非本地变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!