在Python中反思给定函数的嵌套(本地)函数

Wil*_*hen 5 python function introspection inspect

鉴于功能

def f():
    x, y = 1, 2 
    def get():
        print 'get'
    def post():
        print 'post'
Run Code Online (Sandbox Code Playgroud)

有没有办法让我以我可以调用它们的方式访问它的本地get()和post()函数?我正在寻找一个可以使用上面定义的函数f()的函数:

>>> get, post = get_local_functions(f)
>>> get()
'get'
Run Code Online (Sandbox Code Playgroud)

我可以访问那些本地函数的代码对象

import inspect
for c in f.func_code.co_consts:
    if inspect.iscode(c):
        print c.co_name, c
Run Code Online (Sandbox Code Playgroud)

结果

get <code object get at 0x26e78 ...>
post <code object post at 0x269f8 ...>
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何获得实际可调用的函数对象.这甚至可能吗?

谢谢你的帮助,

将.

gav*_*oja 6

你已经非常接近这样做了 - 只是缺少new模块:

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 :].
Run Code Online (Sandbox Code Playgroud)

但为什么要这么麻烦呢?使用class不是更方便吗?无论如何,实例化看起来就像一个函数调用。