31

if I'm in the python console and I want to see how a particular module works, is there an easy way to dump the source?

tehryan
  • 757
  • 3
  • 8
  • 14
  • 1
    the question was wheteher or not there was an easy way to do it from within the console. The inspect module is exactly what I was looking for. – tehryan Jan 15 '10 at 06:00
  • Voting to re-open because the question linked as a duplicate asks about a function rather than a module. The answer is the same, but someone searching for this question would not necessarily ask the other question. – Jim Hunziker Apr 08 '16 at 18:19
  • 2
    This question is not a duplicate. It asks about features of the Python console and not for code inspection. Therefore Michał Marczyk is answering it correctly for the IPython console. – Lukas Jul 04 '18 at 13:23

3 Answers3

45

Some of the methods of inspect module are well-suited for this purpose:

import module
import inspect
src = inspect.getsource(module)
Alok Singhal
  • 93,253
  • 21
  • 125
  • 158
9

Using IPython, you can do this:

In [1]: import pyparsing
In [2]: pyparsing.Word??

...and the source will be displayed, if possible. I guess this must use inspect under the hood, but the added convenience of ? / ?? is fantastic.

Michał Marczyk
  • 83,634
  • 13
  • 201
  • 212
1

Maybe try

print(open('mymodule.py').read())

?

See file.read().

Community
  • 1
  • 1
gimel
  • 83,368
  • 10
  • 76
  • 104