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

后端 未结 12 1873
情话喂你
情话喂你 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
    2020-11-22 03:13

    To expand on runeh's answer:

    >>> def foo(a):
    ...    x = 2
    ...    return x + a
    
    >>> import inspect
    
    >>> inspect.getsource(foo)
    u'def foo(a):\n    x = 2\n    return x + a\n'
    
    print inspect.getsource(foo)
    def foo(a):
       x = 2
       return x + a
    

    EDIT: As pointed out by @0sh this example works using ipython but not plain python. It should be fine in both, however, when importing code from source files.

提交回复
热议问题