Reflect / Inspect closed-over variables in Python

You don't have to use the inspect module here.

>>> dict(zip(f2.func_code.co_freevars, (c.cell_contents for c in f2.func_closure)))
{'x': 2}

works in Python 2.7


You can get the cell contents by checking out f.func_closure (works in Python 2.7.5):

>>> def f(x):
...   def g(y):
...     return x + y
...   return g
... 
>>> f2 = f(2)
>>> [cell.cell_contents for cell in f2.func_closure]
[2]

Python 3.3 has an inspect.getclosurevars function:

Get the mapping of external name references in a Python function or method func to their current values. A named tuple ClosureVars(nonlocals, globals, builtins, unbound) is returned. nonlocals maps referenced names to lexical closure variables, globals to the function’s module globals and builtins to the builtins visible from the function body. unbound is the set of names referenced in the function that could not be resolved at all given the current module globals and builtins.

I'm not yet sure if you can get the closed-over variable names pre-Python 3.3.