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

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

    dis is your friend if the source code is not available:

    >>> import dis
    >>> def foo(arg1,arg2):
    ...     #do something with args
    ...     a = arg1 + arg2
    ...     return a
    ...
    >>> dis.dis(foo)
      3           0 LOAD_FAST                0 (arg1)
                  3 LOAD_FAST                1 (arg2)
                  6 BINARY_ADD
                  7 STORE_FAST               2 (a)
    
      4          10 LOAD_FAST                2 (a)
                 13 RETURN_VALUE
    

提交回复
热议问题