Python: using Sphinx to create project documentation

 

Sphinx is one of the tools that helps you to create project documentation. Here is a quick tutorial on how to use it.

You’ve worked on a project for several weeks now when you decided to generate documentation using the docstrings in your source .py files. Let’s make a little demo project.

Project structure:

myapp/ 
    docs/ 
    myapp/
        app.py
        run.py 
    tests/

Assuming you have already installed Sphinx, goto “myapp” directory and run sphinx-quicksetup or sphinx-quicksetup2 if the project uses python2.

Sphinx will enter an interactive session. During this session it is important to select the following options:

> autodoc: automatically insert docstrings from modules (y/n) [n]: y
> ifconfig: conditional inclusion of content based on config values (y/n) [n]: y

Now, cd into “docs” or the root directory that you’ve selected during interactive session and open “conf.py” with your favourite text editor. Add the following line after import statements:

sys.path.insert(0, os.path.abspath(os.path.pardir))

After that Sphinx will be aware of “myapp” and “tests” directories. Next, edit “index.rst” file and add “modules” keyword in “Contents:” section:

Welcome to myapp's documentation!
========================================
Contents:

   .. toctree::
   :maxdepth: 2

   modules

We are ready to generate our documentation from sources. Run the commands below:

sphinx-apidoc -o . ../myapp/
sphinx-build . myapp_html_docs

When Sphinx build process is finished you can go to “myapp_html_docs” directory and open “index.html” file in your favourite browser to see the results. This is basically all you need to know to start with Sphinx.

SUMMARY:

  • sphinx-quickstart
  • change into root directory created for Sphinx
  • add sys.path.insert(0, os.path.abspath(os.path.pardir)) in conf.py
  • add “modules” in index.rst
  • sphinx-apidoc -o . ../myapp/
  • sphinx-build . myapp_html_docs

TIPS:

Sphinx uses reStructuredText markup language. Therefore, if you want to make your documentation look nice you need to learn about how to use reStructuredText when writing python docstrings.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s