Is there a way to view the source code of a function, class, or module from the python interpreter? [duplicate]
Is there a way to view the source code of a function, class, or module from the python interpreter? (in addition to using help to view the docs and dir to view the attributes/methods)
If you plan to use python interactively it is hard to beat ipython. To print the source of any known function you can then use %psource
.
In [1]: import ctypes
In [2]: %psource ctypes.c_bool
class c_bool(_SimpleCData):
_type_ = "?"
The output is even colorized. You can also directly invoke your $EDITOR
on the defining source file with %edit
.
In [3]: %edit ctypes.c_bool
>>> 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
精彩评论