33

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?

3
  • 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. Commented Jan 15, 2010 at 6: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. Commented Apr 8, 2016 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. Commented Jul 4, 2018 at 13:23

3 Answers 3

49

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

import module
import inspect
src = inspect.getsource(module)
Sign up to request clarification or add additional context in comments.

5 Comments

sometimes doesn't work. for example: see this screenshot: recolic.net/tmp/snap-0508-203529.png
@recolic link has expired
@LuisFelipe I have lost the screenshot... Sorry for that and just ignore my comment plz.
Does not work for "built-in" modules.
Thank you! Ended up using this to peer into pytz.country_names and pytz.lazy 👌
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.

Comments

1

Maybe try

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

?

See file.read().

4 Comments

this dumps the content of any file.
for this to work you would have to be in the directory where the module is placed. Sorta defeats the purpose in my opinion.
You can use __file__ instead of the static string.
__file__ does not work for "built-in" modules

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.