Discovering Python’s Built-in pydoc Module

While writing docstrings for a Python project, I discovered a new way to access package documentation. Previously, I relied exclusively on the Python REPL (Read-Eval-Print Loop) to view this information:

>>> import sys
>>> help(sys)

That was until I learned of a built-in module called pydoc that offers a convenient way to explore the documentation of any Python package directly from your shell.

Using pydoc is straightforward: simply pass in the name of whatever Python package/module/function/etc you want the documentation for, and pydoc will show you its documentation. For example, the following command displays the documentation for the sys module.

$ pydoc sys
Help on built-in module sys:

NAME
sys

MODULE REFERENCE
https://docs.python.org/3.12/library/sys.html
...

You can further explore the documentation of submodules and functions by appending a dotted reference.

$ pydoc sys.platform
Help on str in sys object:

sys.platform = class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If
...

You can even pydoc pydoc if you so desire.

pydoc pydoc
Help on module pydoc:

NAME
pydoc - Generate Python documentation in HTML or text for interactive use.

MODULE REFERENCE
...

Pydoc’s functionality goes beyond displaying help information in the console. You can utilize the -w <name> option to generate an HTML file of the documentation:

$ pydoc -w sys
wrote sys.html

This creates a file named sys.html that you can open and view using any browser. However, this approach has a limitation: it only outputs the documentation for the specified module and not its submodules or related functions.

Fortunately, pydoc offers a more efficient way to explore html documentation. The -n, -p, and -b flags enable you to launch an HTTP server, serving help information for any installed package:

  • -n <hostname>: This flag allows you to specify a hostname for the server.
  • -p <port>: This flag lets you define a port number for the server.
  • -b: This flag opens your web browser and automatically navigates to the server’s address.

For instance, to launch the server on localhost using port number 5432 and have your browser automatically open the documentation, you can use the following command:

$ pydoc -n localhost -p 5432 -b

This approach provides a more interactive and user-friendly way to explore module documentation, allowing you to navigate through submodules and functions seamlessly within your web browser.

I hope this exploration of pydoc has been insightful. Feel free to experiment with its features and share your experiences in the comments below.

Leave a comment