Introspecting a given function's nested (local) functions in Python
function, inspect, introspection, python
Solution
You are pretty close of doing that - just missing `new` module:
import inspect
import new
def f():
x, y = 1, 2
def get():
print 'get'
def post():
print 'post'
for c in f.func_code.co_consts:
if inspect.iscode(c):
f = new.function(c, globals())
print f # Here you have your function :].
But why the heck bother? Isn't it easier to use class? Instantiation looks like a function call anyway.
Problem
Given the function ``` def f(): x, y = 1, 2 def get(): print 'get' def post(): print 'post' ``` is there a way for me to access its local get() and post() functions in a way that I can call them? I'm looking for a function that will work like so with the function f() defined above: ``` >>> get, post = get_local_functions(f) >>> get() 'get' ``` I can access the code objects for those local functions like so ``` import inspect for c in f.func_code.co_consts: if inspect.iscode(c): print c.co_name, c ``` which results in ``` get <code object get at 0x26e78 ...> post <code object post at 0x269f8 ...> ``` but I can't figure out how to get the actual callable function objects. Is that even possible? Thanks for your help, Will.