python - inspect 不适用于 FunctionType 生成的函数

python - inspect doesn't work well with FunctionType generated functions

这是我的代码,我想要的是能够动态生成一些函数并将其打印到文件中。

import types
import inspect

def create_function(name, args):

    def y(a,b,c): 
        print "working!"

    new_varnames = ("d","e","f")

    y_code = types.CodeType(args, \
    y.func_code.co_nlocals, \
    y.func_code.co_stacksize, \
    y.func_code.co_flags, \
    y.func_code.co_code, \
    y.func_code.co_consts, \
    y.func_code.co_names, \
    new_varnames, \
    y.func_code.co_filename, \
    name, \
    y.func_code.co_firstlineno, \
    y.func_code.co_lnotab)


    return types.FunctionType(y_code, y.func_globals, name)

这是输出

>>> myfunc = create_function('myfunc', 3)
>>> myfunc(d=1,e=2,f=3)
working!
>>> print inspect.getsource(myfunc)
    def y(a,b,c): 
        print "working!"

我有点失望,我想换成:

def myfunc(d,e,f):
    print "working!"

怎么可能?

Python 函数对象不包含它们的源代码。它们仅包含 字节代码 ,加上文件名和起始行号(如果它们是从文件加载的)。

您在创建 CodeType() 对象时复制了该元数据:

y.func_code.co_filename,
# ...
y.func_code.co_firstlineno,

Python 然后使用该信息从原始文件加载源;对于回溯和 inspect.getsource()。由于您复制了原始的 y 函数元数据,inspect.getsource() 找到了原始的源文件并返回了 y 的源定义。

您必须生成一个 new 文件,将其写入磁盘,并调整代码对象的 co_filenameco_firstlineno 属性,如果你想产生不同的输出。实际上,没有人为此烦恼。