Photoruction工事中!

Photoructionの開発ブログです!

Pythonコードをドキュメント化した

はじめに

こんにちは、エンジニアの酒井です。

最近、チームで頻繁に使う関数、処理を共通ライブラリとして集約し、そのドキュメントを作成する業務に取り組みました。

調べたところPython製のドキュメントツールであるSphinxを使うと、ソースコードに記載したdocstringから自動でドキュメントを作成できるとのことなので、実際に使用してみました。

手順

ディレクトリ構成は以下のようになっており、sampleディレクトリ内にモジュールを一つ追加しています。

.
├── Dockerfile
├── docker-compose.yml
└── sample
    ├── __init__.py
    └── sample_1.py

1. Dockerfile, docker-compose.ymlの作成

FROM python:3.8

ENV APP_PATH=/code \\
    PYTHONPATH=.

WORKDIR $APP_PATH

RUN apt-get update && \\
    apt-get upgrade -y && \\
    pip install poetry

# `poetry init`をしたいので最初はコメントアウトする
# COPY poetry.lock pyproject.toml ./
# RUN poetry install

COPY . .

EXPOSE 8080
version: '3.8'

services:
  sample:
    container_name: sample
    build:
      context: .
      dockerfile: ./Dockerfile
    ports:
      - "8080:8080"
    tty: true
    volumes:
      - .:/code/
      - ${PIP_CACHE_DIR:-cache-sample}:/root/.cache

volumes:
  cache-sample:

2. poetryの導入、必要ライブラリのインストール

2-1. コンテナ上でbashを起動

$ docker-compose up -d --build
$ docker-compose exec sample bash

2-2. poetryの導入

# poetry init

2-3. 必要ライブラリをインストール

# poetry add sphinx sphinx_rtd_theme
  • sphinxsphinx_rtd_themeをインストールします。
  • pyproject.tomlに上記のライブラリが追記され、poetry.lock が生成されます。

3. ドキュメント作成

3-1. sphinx-apidocコマンドでドキュメント作成に必要なファイルを作成

# poetry run sphinx-apidoc -F -H sample -o docs sample
  • 指定したディレクトリは以下(今回はdocs)にファイルが生成されます。

3-2. 作成された conf.pyの編集

  • conf.pyでは大きく分けて、以下4つの設定が可能。

    1. Path setup(パスの設定)
    2. Project information(プロジェクト情報の設定)
    3. General configuration(一般的な設定)
    4. Options for HTML output(HTML出力に関するオプション)
  • 今回は以下の3つを変更する

    1. pathの指定
    2. 拡張モジュールの追加
      1. sphinx.ext.autodoc
      2. sphinx.ext.viewcode
      3. sphinx.ext.todo
      4. sphinx.ext.napoleon
      5. sphinx_rtd_theme
    3. デザインの設定(sphinx_rtd_theme
    # Configuration file for the Sphinx documentation builder.
    #
    # This file only contains a selection of the most common options. For a full
    # list see the documentation:
    # <https://www.sphinx-doc.org/en/master/usage/configuration.html>
    
    # -- Path setup --------------------------------------------------------------
    
    # If extensions (or modules to document with autodoc) are in another directory,
    # add these directories to sys.path here. If the directory is relative to the
    # documentation root, use os.path.abspath to make it absolute, like shown here.
    #
    
    import sphinx_rtd_theme # sphinx_rtd_themeのインポート
    
    import os # コメントアウトを外す
    import sys # コメントアウトを外す
    
    sys.path.insert(0, os.path.abspath('../')) # パスの指定(conf.pyから見てルートディレクトリを指定する)
    
    # -- Project information -----------------------------------------------------
    
    project = 'sample'
    copyright = '2022, sample'
    author = 'sample'
    
    # -- General configuration ---------------------------------------------------
    
    # Add any Sphinx extension module names here, as strings. They can be
    # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
    # ones.
    extensions = [
        'sphinx.ext.autodoc', # 追加
        'sphinx.ext.viewcode', # 追加
        'sphinx.ext.todo', # 追加
        'sphinx.ext.napoleon', # 追加
        'sphinx_rtd_theme' # 追加
    ]
    
    # Add any paths that contain templates here, relative to this directory.
    templates_path = ['_templates']
    
    # List of patterns, relative to source directory, that match files and
    # directories to ignore when looking for source files.
    # This pattern also affects html_static_path and html_extra_path.
    exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
    
    # -- Options for HTML output -------------------------------------------------
    
    # The theme to use for HTML and HTML Help pages.  See the documentation for
    # a list of builtin themes.
    #
    html_theme = 'sphinx_rtd_theme' # 編集
    html_theme_path = ["_themes", sphinx_rtd_theme.get_html_theme_path()] # 追加
    
    # Add any paths that contain custom static files (such as style sheets) here,
    # relative to this directory. They are copied after the builtin static files,
    # so a file named "default.css" will overwrite the builtin "default.css".
    html_static_path = ['_static']
    

3-2. HTMLファイルをビルドする

$ poetry run sphinx-build docs docs/_build

4. 動作確認

docs/_buildディレクトリに作成されたindex.htmlを確認すると、以下のようなページが出来上がっているのことが確認できる。

  • トップページ
  • モジュールのドキュメント例

5. 公開

これらをGitHubPagesやS3に配置し公開することでSphinxを用いたドキュメントが閲覧することができます。

※ 実際にはGitHub Actionsを用いて docs/_build 配下のファイルをS3にアップロードしてそれをCloudFront経由で配信するという形を取りました。こうすることでソースコードを変更するたびにドキュメントが更新され、運用がより楽になります。

次回記事を書く機会がありましたらまとめたいと思います。

さいごに

ドキュメントの作成をSphinxに任せることで共通ライブラリの管理、運用の手間が省けると感じました!

今後も業務の中で人が行う必要がない部分は積極的に自動化して、自分を含めチームメンバーが本質的な部分に力を注げるよう行動していきたいなと思います!

 

株式会社フォトラクションでは一緒に働く仲間を募集しています