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

后端 未结 12 1852
情话喂你
情话喂你 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:07

    Please mind that the accepted answers work only if the lambda is given on a separate line. If you pass it in as an argument to a function and would like to retrieve the code of the lambda as object, the problem gets a bit tricky since inspect will give you the whole line.

    For example, consider a file test.py:

    import inspect
    
    def main():
        x, f = 3, lambda a: a + 1
        print(inspect.getsource(f))
    
    if __name__ == "__main__":
        main()
    

    Executing it gives you (mind the indention!):

        x, f = 3, lambda a: a + 1
    

    To retrieve the source code of the lambda, your best bet, in my opinion, is to re-parse the whole source file (by using f.__code__.co_filename) and match the lambda AST node by the line number and its context.

    We had to do precisely that in our design-by-contract library icontract since we had to parse the lambda functions we pass in as arguments to decorators. It is too much code to paste here, so have a look at the implementation of this function.

提交回复
热议问题