gpt4 book ai didi

python - 如何检查具有给定名称的变量是否是非本地的?

转载 作者:行者123 更新时间:2023-11-28 21:35:14 25 4
gpt4 key购买 nike

给定一个栈帧和一个变量名,我如何判断该变量是否是非局部变量?示例:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com