How to check if a variable with a given name is nonlocal?

自作多情 提交于 2019-12-06 13:32:30

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

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)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!