概要
みなさんこんにちはcandleです。今回はpythonのSphinxを使ってクラスや関数の説明を自動生成します。
前提
Python3を使って説明しますが、おそらくpython2でも動くと思います。
テストファイルを用意する
main.pyとdog.pyファイルを作成します。
touch main.py dog.py
main.pyに以下を記述します。
from dog import Dog def main(): dog = Dog() dog.show_name() if __name__ == "__main__": main()
dog.pyを開いて以下を記述します。
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
準備は以上です。
Sphinxのインストール
Sphinxはpipでインストールする。
python3を使っているのでpip3コマンドでインストールします。
pip3 install Sphinx
いくつかのsphinxコマンドがグローバルに使えるようになります。
sphinx-apidoc sphinx-autogen sphinx-build sphinx-quickstart
Sphinxの初期化
続いて、Sphinxの初期化を行います。
Sphinx関連のファイルをおくフォルダを作成します。フォルダ名はなんでも良いですが、わかりやすく「docs」にします。
mkdir docs
このようなフォルダ構成になります。__pycache__はpythonのキャッシュファイルです。
sphinx-quickstartを使ってSphinxを初期化します。引数でファイルを展開するフォルダを指定します。
このコマンドを実行するといくつかの対話式のやりとりを行います。
sphinx-quickstart docs
Separate source and build directories (y/n) [n]: はデフォルトの「n」
Name prefix for templates and static dir [_]: はデフォルトの「_」
Project name:
これは自分のプロジェクト名をつけます。今回は「sphinx_dog」と名付けます。
Author name(s):
は適当な名前にします。今回は「alice」とします。
Project version []: はあればそのバージョンなければ、そのままエンター
Project release []: もあれば書いて、なければそのままエンター
Project language [en]: は日本語にしたければjaと入力してエンター
Source file suffix [.rst]: はデフォルト
Name of your master document (without suffix) [index]: はデフォルト
下の質問は全てデフォルト
> 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]: はデフォルト
Create Windows command file? (y/n) [y]: はデフォルト
全て完了したら、docsフォルダにいくつかファイルが作成されます。
初期化は以上です。
自動ドキュメント作成の設定
Sphinxは何も設定しないと、コードから自動的にドキュメントを生成してくれません。いくつか設定します。
docs/conf.pyを開きます。
読み込みパスの変更
conf.pyからみてSphinxにどの場所にあるpythonファイルを読み込むか設定します。
まず、conf.pyの以下の部分をコメントインします。
# import os # import sys # sys.path.insert(0, os.path.abspath('.'))
そのままpathを1つ上のフォルダを指定する。
import os import sys sys.path.insert(0, os.path.abspath('../'))
次に、pythonのコードに記述したdocstringからドキュメントを生成してくれるエクステンションを読み込みます。
extensions = []
を
extensions = ['sphinx.ext.autodoc','sphinx.ext.viewcode']
にします。
sphinx.ext.autodocは関数の説明に以下のdocstringを書くと、自動的にドキュメントを生成してくれます。
A dog will bark ‘Bow Wow’
Example::
from dog import Dog
dog = Dog()
dog.bark()
“””
sphinx.ext.viewcode はドキュメントの関数の場所にソースコードへのリンクを表示してくれます。
# 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']
個々のプロパティの詳しい情報はこちらに書いてあります。
http://www.sphinx-doc.org/ja/stable/ext/autodoc.html
次に、サイドバーに表示するコンテンツを決めます。
下のコードをコメントインして、
# html_sidebars = {}
追加します。
html_sidebars = { '**': [ 'relations.html', # needs 'show_related': True theme option to display 'about.html', 'navigation.html', 'searchbox.html', ] }
Sphinxの設定は以上です。
トップページに各モジュールへのリンクを表示する
トップページはindex.rstになります。これを開いて、toctreeのところにdogを加えます。
.. toctree:: :maxdepth: 2 :caption: Contents: dog
準備ができました。
ドキュメントを作成する
sphinx_dogフォルダで以下を実行するとpythonファイルからrstファイルが作られます。
sphinx-apidoc -f -o ./docs .
次に、rstからドキュメントとなるhtmlを生成します。
sphinx-build -b html ./docs ./docs/_build
完成しました。
docs/_build/index.htmlをダブルクリックしてブラウザで開きます。
このように表示できれば成功です。
クラスと関数にdocstringで説明を書く
現在、Dogクラスのページ移動しても、クラス名と関数が表示されているだけです。
dog.pyを開いて、いくつかsphinx用の記述を加えます。
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
保存したら、再度以下を実行してドキュメントを更新します。
sphinx-build -b html ./docs ./docs/_build
dogクラスのページを見ると説明が追加されています。
ドキュメント生成スクリプト
毎回コマンドを叩くのは面倒なのでpythonのスクリプトを作成します。
touch make_docs.py
中身を以下のようにします。
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()
保存したら、以下のコマンドでドキュメントを作成します。
python3 make_docs.py
まとめ
sphinxのautodocは便利な反面コードが長くなってしまうのはきになるところですね。
rstの構文については以下のリンクが参考になります。
http://docutils.sourceforge.net/docs/user/rst/quickref.html
サンプルはこれが参考になります。
https://thomas-cokelaer.info/tutorials/sphinx/docstring_python.html