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

后端 未结 12 1866
情话喂你
情话喂你 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
    
    0 讨论(0)
  • 2020-11-22 02:59

    The inspect module has methods for retrieving source code from python objects. Seemingly it only works if the source is located in a file though. If you had that I guess you wouldn't need to get the source from the object.

    0 讨论(0)
  • 2020-11-22 02:59

    to summarize :

    import inspect
    print( "".join(inspect.getsourcelines(foo)[0]))
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 03:02

    If you are using IPython, then you need to type "foo??"

    In [19]: foo??
    Signature: foo(arg1, arg2)
    Source:
    def foo(arg1,arg2):
        #do something with args
        a = arg1 + arg2
        return a
    
    File:      ~/Desktop/<ipython-input-18-3174e3126506>
    Type:      function
    
    0 讨论(0)
  • 2020-11-22 03:03

    I believe that variable names aren't stored in pyc/pyd/pyo files, so you can not retrieve the exact code lines if you don't have source files.

    0 讨论(0)
提交回复
热议问题