开发者

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

This question already has answers here: 开发者_运维百科 How can I get the source code of a Python function? (13 answers) Closed 8 years ago.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜