Python 3.3+inspectfunction
inspect.getclosurevars()
classes and functions
Shows which outside names a function refers to: closure, global, built-in and unresolved ones, as a ClosureVars named tuple.
Syntax
inspect.getclosurevars(func)
Values are read when getclosurevars runs, not when the function was defined. unbound is not just typos: the function looks at every name in the code, so an attribute name (x.real) ends up there too although nothing is wrong. unbound is a set, so sort it before printing. Built-in functions raise TypeError.
Examples
import inspect
rate = 2
def make(k):
def f(x):
return x.real * k * rate + len([]) + undefined_name
return f
cv = inspect.getclosurevars(make(3))
print(cv.nonlocals, cv.globals) # → {'k': 3} {'rate': 2}
print(list(cv.builtins), sorted(cv.unbound)) # → ['len'] ['real', 'undefined_name']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy