作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
给定一个栈帧和一个变量名,我如何判断该变量是否是非局部变量?示例:
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
,它是代码对象使用的闭包变量名称的元组:
def is_nonlocal(frame, varname):
return varname in frame.f_code.co_freevars
请注意,这是专门的闭包变量,即 nonlocal
语句查找的那种变量。如果要包含所有非局部变量,则应检查 co_varnames
(内部范围内未使用的局部变量)和 co_cellvars
(内部范围内使用的局部变量):
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
。
关于python - 如何检查具有给定名称的变量是否是非本地的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52504979/
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 4 年前。
我已更改 my.cnf。并检查sql_mode使用下面的命令 select @@global.sql_mode; 它说, 我也尝试过 set global sql_mode=''; SET sql_m
首先,我有一个结构,它有一个值和一个默认值 struct S { int a = 1; }; 当 gcc 和 clang 都是 non-const/non-constexpr 时,可以默认构造
我是一名优秀的程序员,十分优秀!