如何检查具有给定名称的变量是否为非本地变量? [英] How to check if a variable with a given name is nonlocal?

查看:176
本文介绍了如何检查具有给定名称的变量是否为非本地变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个堆栈框架和一个变量名,如何判断该变量是否为非本地变量?示例:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆