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

后端 未结 12 1990
情话喂你
情话喂你 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 02:57

    If you're strictly defining the function yourself and it's a relatively short definition, a solution without dependencies would be to define the function in a string and assign the eval() of the expression to your function.

    E.g.

    funcstring = 'lambda x: x> 5'
    func = eval(funcstring)
    

    then optionally to attach the original code to the function:

    func.source = funcstring
    

提交回复
热议问题