[python]Sphinx Docstring

JIN

October 14, 2021

Sphinx 설치

파이썬 코드 독스를 작성하기 위해 Sphinx를 사용하기로 했다.
출력 포맷이 문서뿐만 아니라 html도 호환이 가능하다는 장점이 있다.
먼저 사용을 위해서는 sphinx 라이브러리를 설치해 주어야 한다.

# pip install sphinx

Docstring 작성을 위한 Sphinx 셋팅

Sphinx 라이브러리 설치가 완료되었다면 기본 셋팅이 필요하다.

  1. quickstart 명령어를 통해 Docs 디렉토리를 생성한다.
  2. *.rst 파일을 변환하여 Docs 파일을 생성한다.
  3. make html 명령어를 통해 python 코드 컴파일 후 html 파일을 생성한다.

디렉토리 생성

# cd docs
# sphinx-quickstart
...


You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/n) [n]: y

The project name will occur in several places in the built documentation.
> Project name: project name
> Author name(s): your name
> Project release []: version

...

For a list of supported codes, see
https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language.
> Project language [en]: ko



폴더별로 정리되어 있는 것을 선호해서 프로젝트 경로 내에 docs 라는 폴더를 생성한 후 진행했다.

Separate source and build directories (y/n) [n]: y

*.rst 파일 생성 및 셋팅

# conf.py

# 해당 부분의 주석 해제 후 경로를 지정해 준다.
import os
import sys
sys.path.insert(0, os.path.abspath('../../'))

...

# extensions 에 아래와 같이 추가해 준다.
# sphinx.ext.autodoc : 문서화 할 모듈을 import하기 위해 사용
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest',
              'sphinx.ext.intersphinx', 'sphinx.ext.todo',
              'sphinx.ext.ifconfig', 'sphinx.ext.viewcode',
              'sphinx.ext.inheritance_diagram',
              'sphinx.ext.autosummary']

# cd ..
# sphinx-apidoc.exe -f -o docs/source .

이제 docs/source 경로에 *.rst 파일이 생성된 것을 확인할 수 있다.

# docs/source/index.rst

Welcome to (your project) documentation!
==========================================

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

docs 빌드

make 명령어를 통해 생성된 코드와 *.rst 파일을 docs 로 변환한다.

# docs\make.bat html

docstring 포맷 설정

sphinx 는 기본적으로 reST(reStructuredText) 스타일만 지원한다.

NumPy 또는 Google 스타일을 사용을 위해서는 추가적인 설치와 설정이 필요하다.

# pip install sphinxcontrib-napoleon
# conf.py

# 아래와 같이 추가
extensions = ['sphinxcontrib.napoleon']

sphinx 사용 예시

https://github.com/5xJIN/sphinx_example

테마 설정

html 빌드 시 해당 페이지에 대한 테마를 지정할 수 있다.
링크에 접속하면 여러가지 sphinx 테마 목록이 있는데 취향에 맞게 테마 install 후 지정하여 사용하면 된다.
내가 예시로 사용한 테마는 Material 로 이 테마를 기준으로 설정 방법을 설명할 예정이다. 또는 각 테마의 데모 페이지에 접속하면 적용 방법이 있으므로 보고 따라하는 것을 추천한다.

테마 라이브러리 설치

pip install sphinx-material

테마 설정

#conf.py

html_theme = 'sphinx_material'

설정 파일 내에 테마 설정까지 마친 후 재빌드를 하면 테마가 적용된 것을 확인할 수 있다.

메인 화면

docstring 적용 화면