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

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


If the function is from a source file available on the filesystem, then inspect.getsource(foo) might be of help:

If foo is defined as:

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

Then:

import inspectlines = inspect.getsource(foo)print(lines)

Returns:

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

But I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.


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.


The following tests inspect.getsource(foo) using Python 3.6:

import inspectdef foo(arg1,arg2):    #do something with args    a = arg1 + arg2    return asource_foo = inspect.getsource(foo)  # foo is normal functionprint(source_foo)source_max = inspect.getsource(max)  # max is a built-in functionprint(source_max)

This first prints:

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

Then fails on inspect.getsource(max) with the following error:

TypeError: <built-in function max> is not a module, class, method, function, traceback, frame, or code object


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 aFile:      ~/Desktop/<ipython-input-18-3174e3126506>Type:      function


matomo