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

392 Views Asked by At

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()
1

There are 1 best solutions below

0
On BEST ANSWER

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.