2022年3月16日水曜日

Python のプロジェクト?で sphinx.ext.autodoc を使ってみた

久し振りに 新しく python で作業したので、感想をちょっとアップしてみる。 (前回からかなり開いたので、中身半端だがとりあえず)

きっかけは、 4年ほど前に作った php のスクリプトが、 今年になって、サーバー側が php を対象外にしたために動かなくなったこと。 そこで、サポートが継続している python でやってみた次第。

スクリプト自体は短かく、ハードルが低いので、ものは試しと、 ドキュメント作成に sphinx.ext.autodoc に挑戦してみた。で、その感想。

sphinx.ext.autodoc は、 docstring でドキュメントが書かれたモジュールから、 docstring を読みこみ、半自動的にドキュメント(マニュアル)を作成させるしくみで、 物忘れが激しい隠居老人には便利かもと期待が、少し、あった。

1 ディレクトリ構成

作業は 以下のようなディレクトリで行なった。 環境は、Debian 5.10, python3.9.9, pipenv, Sphinx 4.4.0。

.
├── AUTHORS.rst
├── CONTRIBUTING.rst
├── HISTORY.rst
├── LICENSE
├── Pipfile
├── Pipfile.lock
├── README.rst
├── data
├── docs
│   ├── Makefile
│   ├── _build
│   ├── _static
│   ├── _templates
│   ├── apis
│   │   ├── forecasting.rst
│   │   ├── main.rst
│   │   └── modules.rst
│   ├── authors.rst
│   ├── conf.py
│   ├── contributing.rst
│   ├── history.rst
│   ├── index.rst
│   ├── readme.rst
│   └── usage.rst
├── logs
│   ├── met_norway.log
│   ├── met_norway.log.1
│   ├── met_norway.log.2
│   └── met_norway.log.3
└── metonoの
    ├── forecasting.py
    └── main.py

2 導入、設定

project ディレクトリのトップで、 以下のコマンドで sphinx を導入する。 ドキュメントのソースとビルド結果は同じディレクトリになってしまう (選択メニューが表われない)。

$ sphinx-apidoc -a -F -o ./docs ./src

通常は、 ‘$ sphinx-quickstart docs’ みたいなコマンドなのだが、 うまくいかず、今回は、apidoc でやってみて、やっと前にすすめた。

path がうまく通らなくて、 module が見つからないと幾度となくしかられ、疲弊した末の結果。

conf.py は以下の項目をとりあえず編集すればよし。 numpy や 、google スタイルを使う場合は、それぞれの 、extention を追加する。

  • プロジェクト名
  • 作者
  • リリースバージョン
  • プロジェクトの言語は、`ja`
  • extensions(最低限は自動でセットされている)

ソースコードを更新するには、 プロジェクトディレクトリのトップで、以下。 私は、 apis というディクトリを用意して、 ここに、ソースコード関連を収めるよう修正した。これにともなって index.rst も修正。

$ sphinx-apidoc -a -f -o ./docs/apis ./src

あとは適宜、`make html` とかすればドキュメントが作成される。 自動更新もできるみたいだが、チープな環境なのでやらない。

3 感想

  • docstring は、雛形だけだと warning が出るので、項目だけというのや止めよう。

  • autodoc で初期作成したとき、sys.path が自動で追加されていて、 単純にフルパスで追加する記述になっていた。これで通る、というのが判るまで時間がかかった。

    sphinx は、ドキュメントルートから上を参照できないらしいので、 外部リンク扱いでフルパス記述ということなのかな??

  • todo のディレクティブでは、pydoc のドキュメント内で有効。 なので、Bug ってる箇所の近くにかいてもだめ。

  • ソースで、 `main.py` を使う時は、 src ディレクトリのトップに置く必要があるみたい。

  • 検索で日本語が使えないと思い込んでいたのだが、 Mecab を使ったインデックス作成を指定すれば可能になる(感謝、感謝)。 ドキュメントちゃんと読みます、といつも懺悔。

  • デフォルトで使えるテーマは、サイドバーとか使いにくいと感じていたが、 今回、 sphinx-book · GitLab を使って、向上した印象強し。 今後はこれにするかも。 カスタマイズがキモなんろうが、私には、まあ無理。

  • 他のプロジェクトにも、docstring を追加してみようとしたが、 気力が続かない。docstring を癖にせんとあかん、と思った。

最後に、今の conf.py。

# 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 sys

# sys.path.insert(0, os.path.abspath('..'))  # これダメ
sys.path.insert(0, '/home/hogehoge/Documents/proj/met_norway/metono')

# -- Project information -----------------------------------------------------

project = 'Get and Put Weather Forecasting Data.'
copyright = '2022, ayage'
author = 'ayage'

# The full version, including alpha/beta/rc tags
release = '2.0.1'


# -- 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.autosummary',
    # 作成中のシステムのdocstringが長く、詳細まで記述されていて、
    # 読みやすくするためにページを分けて出力されている場合に便利らしい
    #
    # 'sphinx.ext.intersphinx',
    # 他のプロジェクトのオブジェクトのドキュメントに対して、自動リンクを生成
    # 'sphinx_autodoc_typehints',  # typehint は使ってない
    # 'sphinx.ext.linkcode',
    # インターネット上のどこかにソースコードがある
    'sphinx.ext.ifconfig',
    # 引数として与えられているPythonの式が、プロジェクトの設定ファイルの名前空間の中で評価されたときに、
    # Trueとなった場合のみ、指定されたコンテンツをドキュメントの中に追加
    'numpydoc',
    # Pythonのドキュメントコメントの書き方、NumPyスタイルを使う。
    # 'sphinx.ext.napoleon',
    # pre-processor that parses NumPy and Google style docstrin
    # NumPy および Google スタイルの docstring をドキュメントに取り込む
    'sphinx.ext.viewcode',
    # オブジェクトが含まれるソースコードを探しに行きます。
    # もし見つかれば、それぞれのモジュールごとにハイライトされたソースコードのHTMLページを出力
    'sphinx.ext.todo', # Todoアイテムのサポート
    # Add directive for use fontawesome
    # 'sphinx_fontawesome',
]

# 以下は数式、ダイアグラム関係。

# extensions += [
#     'sphinx.ext.graphviz'
# ]

# autodoc ______________________________________________

# 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']
# autodoc_default_flags = ['members', 'private-members']

autodoc_default_options = {
    'members': 'var1, var2',
    'member-order': 'bysource',
    'special-members': '__init__',
    'undoc-members': True,
    'exclude-members': '__weakref__'
}

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

numpydoc_show_class_members = False
# generate autosummary even if no references
autosummary_generate = False
# autosummary_imported_members = True
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']

# The master toctree document.
master_doc = 'index'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'ja'

# 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', 'logs', 'toml', '.git', 'archives']

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# 検索を日本語でできるようにする。-------------------------------------------
# Mecab を使えばよいらしい  https://dev.classmethod.jp/articles/sphinx-using-mecab/

html_search_language = 'ja'
html_search_options = {
 'type': 'sphinx.search.ja.MecabSplitter',
 'dic_enc': 'utf-8',
 'dict': '/usr/lib/x86_64-linux-gnu/mecab/dic/mecab-ipadic-neologd',
}

# -- 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 = 'sphinxdoc'
# html_theme = 'agogo'
# html_theme = 'sphinx_rtd_theme'
html_theme = 'sphinx_book_theme'

# 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']

# -- Options for todo extension ----------------------------------------------

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

Emacs の lsp の設定、なう(202310)

前回さらしてから、さらに1年。そう、3年めになる。 が、今回は一段と自信がない。 環境は、 Debian GNU/Linux 12 (bookworm) + emacs(29.1)。consult + company。 embark は未だに使ってない。 用途は、メモ と ...