Is there a way to view the source code of a function, class or module from a python interpreter?

Is there a way to view the source code of a function, class or module from a python interpreter? (in addition to using help to view documents and dir to view attributes / methods)

+5
source share
2 answers
>>> import inspect
>>> print(''.join(inspect.getsourcelines(inspect.getsourcelines)[0]))
def getsourcelines(object):
    """Return a list of source lines and starting line number for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a list of the lines
    corresponding to the object and the line number indicates where in the
    original source file the first line of code was found.  An IOError is
    raised if the source code cannot be retrieved."""
    lines, lnum = findsource(object)

    if ismodule(object): return lines, 0
    else: return getblock(lines[lnum:]), lnum + 1
+8
source

If you plan on using python interactively, ipython is hard to run . To print the source of any known function, you can use %psource.

In [1]: import ctypes
In [2]: %psource ctypes.c_bool
class c_bool(_SimpleCData):
_type_ = "?"

The conclusion is even colorized. You can also directly call yours $EDITORin the defining source file with %edit.

In [3]: %edit ctypes.c_bool
+15

All Articles