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

后端 未结 12 1849
情话喂你
情话喂你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 03:16

    Since this post is marked as the duplicate of this other post, I answer here for the "lambda" case, although the OP is not about lambdas.

    So, for lambda functions that are not defined in their own lines: in addition to marko.ristin's answer, you may wish to use mini-lambda or use SymPy as suggested in this answer.

    • mini-lambda is lighter and supports any kind of operation, but works only for a single variable
    • SymPy is heavier but much more equipped with mathematical/calculus operations. In particular it can simplify your expressions. It also supports several variables in the same expression.

    Here is how you can do it using mini-lambda:

    from mini_lambda import x, is_mini_lambda_expr
    import inspect
    
    def get_source_code_str(f):
        if is_mini_lambda_expr(f):
            return f.to_string()
        else:
            return inspect.getsource(f)
    
    # test it
    
    def foo(arg1, arg2):
        # do something with args
        a = arg1 + arg2
        return a
    
    print(get_source_code_str(foo))
    print(get_source_code_str(x ** 2))
    

    It correctly yields

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

    See mini-lambda documentation for details. I'm the author by the way ;)

提交回复
热议问题