joppot

コピペで絶対動く。説明を妥協しない

プログラミング

Using sphinx how to generate documents of python classes and functions

投稿日:2018年3月31日 更新日:


Abstruct

Hello everyone it’s me candle. In this article I will explain how to make documents about classes and functions with Sphinx automatically.

condition

I will explain it using Python 3, but I think that it will probably work with python 2 as well.


Prepare test files

Create a main.py and dog.py.

touch main.py dog.py

Write this to the main.py

from dog import Dog

def main():
  dog = Dog()
  dog.show_name()

if __name__ == "__main__":
  main()

Open the dog.py and write it.

class Dog(object):
  def __init__(self, name="bob"):
    self.name = name

  def bark():
    print("Bow Wow")

  def show_name(self):
    print(self.name)

  def get_name(self):
    return self.name

  def set_time(self, name):
    self.name = name

It’s ok.

Install Sphinx

Sphinx is installed by pip.
Since we are using python 3, install it with pip3 command.

pip3 install Sphinx

We can use some sphinx commands as a global.
sphinx-apidoc sphinx-autogen sphinx-build sphinx-quickstart

Setup Sphinx

Next we start to set up Sphinx.
Create a folder to place Sphinx’s files.

mkdir docs

This is the folder structure. __pycache__ is a python cache folder.

We setup Sphinx with a sphinx-quickstart command.
You pass the value where you want to expand the Sphinx files
After running this command, it starts to do interactive interactions.

sphinx-quickstart docs

Separate source and build directories (y/n) [n]: is “n” of default
Name prefix for templates and static dir [_]: is “_” of default

Project name:

You give the name of your project. In this time we type “sphinx_dog”.

Author name(s):

Type your favorite name. I choose a name “alice”.

Project version []: If so, you specify the version. If not, just press the enter.
Project release []: If so, you specify the relese. If not, just press the enter.
Project language [en]: Press the enter
Source file suffix [.rst]: is default
Name of your master document (without suffix) [index]: is default

All the questions below are default

> autodoc: automatically insert docstrings from modules (y/n) [n]:
> doctest: automatically test code snippets in doctest blocks (y/n) [n]:
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]:
> todo: write “todo” entries that can be shown or hidden on build (y/n) [n]:
> coverage: checks for documentation coverage (y/n) [n]:
> imgmath: include math, rendered as PNG or SVG images (y/n) [n]:
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]:
> ifconfig: conditional inclusion of content based on config values (y/n) [n]:
> viewcode: include links to the source code of documented Python objects (y/n) [n]:
> githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]:

Create Makefile? (y/n) [y]: is default.
Create Windows command file? (y/n) [y]: is default.

After finish settings, some files are created in the docs folder.

Setup is over.

Automatic Document Creation Settings

If you do nothing, Sphinx won’t make a document from a code automatically.
So let’s start configuration.

Open a docs/conf.py

Change reference path of Sphinx

Describe the location of the python file to read.
First comment in the following part of conf.py.

# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))

Specify a path that is the parent folder.

import os
import sys
sys.path.insert(0, os.path.abspath('../'))

Next, Read extensions which generates a document from docstring written in python code.

From

extensions = []

To

extensions = ['sphinx.ext.autodoc','sphinx.ext.viewcode']

sphinx.ext.autodoc automatically generates a document written in a docstring in the function etc.

“””
A dog will bark ‘Bow Wow’

Example::

from dog import Dog
dog = Dog()
dog.bark()

“””

sphinx.ext.viewcode will display a link to the source code at the function description.

Write the following code under it.

# Include Python objects as they appear in source files
# Default: alphabetically ('alphabetical')
autodoc_member_order = 'bysource'
# Default flags used by autodoc directives
autodoc_default_flags = ['members', 'show-inheritance']

Each detail properties are writtein in this post.
http://www.sphinx-doc.org/ja/stable/ext/autodoc.html

Next we decide the content to display in the sidebar.

From

# html_sidebars = {}

To

html_sidebars = {
    '**': [
        'relations.html',  # needs 'show_related': True theme option to display
        'about.html',
        'navigation.html',
        'searchbox.html',
    ]
}

The setting of phinx is over.

Display a link to each modules on the top page

Top page is index.rst. Open it and add “dog” to the toctree.

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   dog


Create a document

In the sphinx_dog folder execute the command, an rst file is created from the python file.

sphinx-apidoc -f  -o ./docs .

Let’s create a html file as a document from rst file.

sphinx-build -b html ./docs ./docs/_build

Double-click docs/_build/index.html to open it in your browser.

It is a success if it can be displayed like this.


Write descriptions in docstring for classes and functions

Now, you move to the page of the Dog class, the class name and function are only displayed.

Open the dog.py, add some sphinx descriptions.

class Dog(object):
  """
    This is a very simple Dog class.
   This class can change the name of a dog, get it, or let the dog bark.

    :param name: Dog name, Default is *bob*
    :type name: str

    Example::

        from dog import Dog
        dog = Dog()
  """

  def __init__(self, name="bob"):
    self.name = name

  def bark():
    print("Bow Wow")

  def show_name(self):
    print(self.name)

  def get_name(self):
    return self.name

  def set_time(self, name):
    """
    It returns a Dog class' name value .

    :param name: New Dog name
    :type name: str
    """

    self.name = name

After saving, execute the following again to update the document.

sphinx-build -b html ./docs ./docs/_build

An explanation is added in the page of the dog class.


Document generation script

Since it is troublesome to run a command each time, we will create a python script.

touch make_docs.py

Write it.

import subprocess

def run():
  cmd_api = "sphinx-apidoc -f -o ./docs ./"
  cmd_doc = "sphinx-build -b html ./docs ./docs/_build"

  for cmd in [cmd_api, cmd_doc]:
    result = res = subprocess.Popen(cmd, shell=True, universal_newlines=False)
    print(result)

if __name__ == '__main__':
  run()

Create a document with the following command.

python3 make_docs.py

Conclusion

sphinx ‘s autodoc is convenient, but its code gets lengthened.

For the syntax of rst, the following links are helpful.

http://docutils.sourceforge.net/docs/user/rst/quickref.html

This is a good sample.

https://thomas-cokelaer.info/tutorials/sphinx/docstring_python.html

スポンサードリンク

If you think this article is good, share it please

-プログラミング
-

執筆者:


comment

Your email address will not be published. Required fields are marked *

関連記事

Ruby regex that does not match if there are keywords that you don’t want included in the string

Abstract Hello everyone it’s me candle. In this time I would like to create a regular expression that does not pass if keywords that I do not want included in the string match. This is such case like this. For example, the regex matches these words “Bitcoin” and “Bitcoin ~” but doesn’t match “BitcoinCash” and “Bitcoin Cash”. ○ Bitcoin ○ Bitcoin Core × BitcoinCash × Bitcoin Cash Condition Nothing Write the regex This is a regex that does not match if there are keywords that you do not want included in the string. /Keyword to include(?!Keywords you do not want …

Tutorial How to use GSAP animation with React

Abstract Hello everyone it’s me candle. In this time we will use GSAP in React. The famous js library which can easily use animation is jQuery. However, it seems that compatibility between jQuery and React is bad. And there are no functions Also, as far as I know, React has no animation function that is easy to use(Yeah, Transition is). But, all times and places, it is rare case that animation is not necessary when you have created a web service. There are many candidates when using animation with React. Of course, you can import only the necessary functions and use …

React creates dummy data using Faker.js

Abstract Hello everyone it’s me candle. Let’s try to use Faker.js in React. I think that there are various purposes for using Faker.js. In many cases you will use it for testing, but this time I’d like to create a dummy react state using Faker.js. Condition You have a basic react skill create-react-app was installed Create new project First of all, create a react project. Execute the below command in your favorite directory and create a new react project. create-react-app faker-demo cd faker-demo Installation of faker Install faker with this coommand. yarn add –dev faker it’s over. Generate dummy data …

Remove or allow the html tag with javascript + React and take measures against XSS

Abstract Hello everyone it’s me candle. In this time, we will write a program which displays only the permitted html tags by React and delete other tags. Notice, displaying originally html contents, it may has a security risk such as XSS. First of all, I am not a security expert, so there is a possibility of a bug in the code. Of course, I check it and test it as long as I do. If you find any vulnerabilities in the code, it would be helpful if you point out it in the post comment form. Condition Nothing Preparation of …

How to fix the background scroll of react-modal

Abstract Hello everyone it’s me candle. This time I will solve the react-modal background moving problem when you scroll. Condition You use react Completed sample code If you want to run the sample code actually, you would need to install two libraries before. faker is installed for dummy data generation. yarn add faker react-modal First, I will write the sample code of the completed version. This is described in src/App.js. import React, { Component } from 'react' import Faker from 'faker' import Modal from 'react-modal' Modal.setAppElement('#root') class App extends Component { constructor(props) { super(props) this.state = { users: [], user: …


I work in the venture company as a CTO. I start to write program in University, first I learned java, C++ and PHP. In the company, I'm developing web services by Rails. I do like to automation.