Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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)

like image 714
user379260 Avatar asked Jun 29 '10 19:06

user379260


People also ask

How do you view the source code of a function in Python?

We use the getsource() method of inspect module to get the source code of the function. Returns the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string.

What is the source code in Python?

In simple we can say source code is a set of instructions/commands and statements which is written by a programmer by using a computer programming language like C, C++, Java, Python, Assembly language etc. So statements written in any programming language is termed as source code.


2 Answers

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
like image 128
Benjamin Bannier Avatar answered Sep 23 '22 06:09

Benjamin Bannier


>>> 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
like image 20
Duncan Avatar answered Sep 23 '22 06:09

Duncan