Viewing the code of a Python function [duplicate]

安稳与你 提交于 2019-12-19 05:15:02

问题


Let's say I'm working in the Python shell and I'm given a function f. How can I access the string containing its source code? (From the shell, not by manually opening the code file.)

I want this to work even for lambda functions defined inside other functions.


回答1:


inspect.getsource
It looks getsource can't get lambda's source code.




回答2:


Not necessarily what you're looking for, but in ipython you can do:

>>> function_name??

and you will get the code source of the function (only if it's in a file). So this won't work for lambda. But it's definitely useful!




回答3:


maybe this can help (can get also lambda but it's very simple),

import linecache

def get_source(f):

    source = []
    first_line_num = f.func_code.co_firstlineno
    source_file = f.func_code.co_filename
    source.append(linecache.getline(source_file, first_line_num))

    source.append(linecache.getline(source_file, first_line_num + 1))
    i = 2

    # Here i just look until i don't find any indentation (simple processing).  
    while source[-1].startswith(' '):
        source.append(linecache.getline(source_file, first_line_num + i))
        i += 1

    return "\n".join(source[:-1])



回答4:


A function object contains only compiled bytecode, the source text is not kept. The only way to retrieve source code is to read the script file it came from.

There's nothing special about lambdas though: they still have a f.func_code.co_firstline and co_filename property which you can use to retrieve the source file, as long as the lambda was defined in a file and not interactive input.



来源:https://stackoverflow.com/questions/4014722/viewing-the-code-of-a-python-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!