Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检查具有给定名称的变量是否为非局部变量?_Python_Python 3.x_Stack Frame_Python Nonlocal - Fatal编程技术网

Python 如何检查具有给定名称的变量是否为非局部变量?

Python 如何检查具有给定名称的变量是否为非局部变量?,python,python-3.x,stack-frame,python-nonlocal,Python,Python 3.x,Stack Frame,Python Nonlocal,给定堆栈帧和变量名,如何判断该变量是否为非局部变量?例如: 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 as

给定堆栈帧和变量名,如何判断该变量是否为非局部变量?例如:

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
请注意,这就是闭包变量,
非局部
语句查找的变量类型。如果要包含所有非本地变量,应检查
co\u varnames
(内部范围中未使用本地变量)和
co\u cellvars
(内部范围中使用的本地变量):


另外,不要把东西与
co_name
混在一起,这是目前错误记录的。
inspect
文档说
co_name
是用于局部变量的,但是
co_name
是一种“其他一切”的垃圾箱。它包括全局名称、属性名称和导入中涉及的几种名称-大多数情况下,如果执行需要名称的字符串形式,则会使用
co\u名称

如果是非本地的,则应将
varname
放在
框架中。f\u locals
?@WillemVanOnsem:我有一个输入错误,我一两分钟就修好了。相关/重复@让·弗朗索瓦·法布:相关,但不是重复。然而,答案似乎非常非常错误
f_back
给出调用者的框架(动态范围),而不是定义者的框架(词汇范围)!!!注意,我没有结束这个问题:)哦,duh!!非常感谢。
def isnt_local(frame, varname):
    return varname not in (frame.f_code.co_varnames + frame.f_code.co_cellvars)