views:

95

answers:

2

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)

+2  A: 

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
honk
also can use `ctypes.c_bool??`
gnibbler
couldn't accept it as the regular answer, but yea, ipython is tempting.
@wkat12, ipython is fantastic, why limit yourself to the shell that comes with Python?
gnibbler
@gnibbler: i dunno, i thought that it was attached to the scipy/numpy modules, and those were taking longer for me to understand than I was ready for, but it looks like it's separate (now). also if you're programming code that can be run from the terminal, you'd probably have to watch out for any incompatibilities. might try it again anyhow tho :)
+3  A: 
>>> 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
Duncan
wow.. too bad we need an import, a print, a join, and an index just to make it readable... still, thanks*edit*i played around with the inspect module after reading this, it looks like you can use "getsource" instead of "getsourcelines" and skip the indexing, i.e. print(''.join(inspect.getsource(obj)))