How can I get the source code of a Python function?

后端 未结 12 2054
情话喂你
情话喂你 2020-11-22 02:39

Suppose I have a Python function as defined below:

def foo(arg1,arg2):
    #do something with args
    a = arg1 + arg2
    return a

I can g

12条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 03:06

    If the function is from a source file available on the filesystem, then inspect.getsource(foo) might be of help:

    If foo is defined as:

    def foo(arg1,arg2):         
        #do something with args 
        a = arg1 + arg2         
        return a  
    

    Then:

    import inspect
    lines = inspect.getsource(foo)
    print(lines)
    

    Returns:

    def foo(arg1,arg2):         
        #do something with args 
        a = arg1 + arg2         
        return a                
    

    But I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.

提交回复
热议问题