The Python Help System

A few years ago I had an interview with a company using Python for their main product. At the time I was a beginner, so I wasn’t able to answer all their questions. One of the questions I choked on was this:

– If you’re given a new Python package and you don’t know how it works, how would you figure it out?

I said I would Google it and see if there was any documentation online. They followed up with:

– What would you do if you had no internet connection?

I told them I would read the code and see what I could learn from it. That wasn’t the answer they were looking for.

Python’s online help system

Python includes a built-in help system based on the pydoc module. In a terminal, type:

A help page will be printed to the console:

All pydoc does is generate the help page based on the docstrings in the module.

Happily, you’re not stuck scrolling through the terminal, man page-style. You can start a local web server that serves the documentation in HTML format by typing:

Now if you go to http://localhost:8000  in your browser you will see an index page with links to the documentation pages for all the modules and packages installed on your system.

It will look something like this:


Getting help in IDLE

In the REPL (IDLE or whatever alternative you are using), you can access the same help using the dir  built-in function. This function is added to the built-in namespace (the things that are already defined when the interpreter starts up) by the site  module, which is automatically imported during initialization.

Running these commands in IDLE will print the same help as the pydoc command above:

Checking the attributes on an object

Sometimes you don’t need the full help text. You only want to see what attributes a certain object has so that you can get on with writing code. In that case, the dir command can come in handy.

dir  works in two modes. The first is when it is invoked without any arguments. In that mode, it prints out a list of the names defined in the local scope.

The second is when it is given an object as an argument. In that mode, it tries to return a list of relevant attributes from the object passed in to it. What that means depends on whether the object is a module or a class.

If it’s a module, dir  returns a list of the module’s attributes. If it’s a class, dir  returns a list of the class attributes, and the attributes of the base classes.

A more useful dir function

Usually when I need dir , I also want to know the types of the object’s attributes. Here’s a function that annotates the output of the normal dir  function with the string names of the types of each returned attribute:

I’ll leave it there for now. Don’t forget to play around with the help system to get a feel for it. You’ll be glad of it next time you’re stuck somewhere without an internet connection and want to do some coding.