[Python3] 주석

Alexandria·2023년 8월 31일
0

Python3 Basic

목록 보기
17/19
post-thumbnail

1. Comment

주석(comment)은 코드 내에서 프로그래머가 작성하는 설명문입니다. 주석은 프로그램을 이해하고 사용하는 데 도움이 되며, 코드의 기능과 목적을 더욱 명확하게 전달할 수 있습니다.

주석은 # 기호로 시작하며, 이 기호 뒤에 작성된 모든 텍스트는 주석으로 간주됩니다. 주석은 단일 행 또는 여러 행에 걸쳐 작성될 수 있습니다.

# This is a single line comment
# and is not code
# print('Hello, World!')

여러 행 주석의 경우, 작은따옴표 또는 큰따옴표 3개로 주석을 감싸서 표시할 수 있습니다.

"""
This is a multi-line comment.
It can span multiple lines.
"""

2. Docstring

Docstring은 모듈, 클래스, 함수 또는 메서드 등의 설명서를 작성하는데 사용되는 문자열입니다.

💡 Python의 docstring은 PEP 257에서 자세히 확인할 수 있습니다.

다음과 같이 Python 파일(mymodule.py)의 대한 설명은 파일의 맨 위에 작성하며 함수의 인수와 반환값에 대한 설명은 함수 내부에 작성합니다.

"""
Description of mymodule.py

Usage:
    add(a, b)
"""

def add(a: int, b: int) -> int:
    """
    Add two numbers.

    :param int a: first number
    :param int b: second number
    :return: sum of two numbers
    """
    return a + b

2.1. Sphinx

sphinx는 Python의 Docstring 기능을 사용하여 함수, 클래스 등의 문서화를 지원하는 문서 생성 도구로

Python 코드와 reStructuredText 포맷으로 작성된 문서를 바탕으로 HTML, PDF, EPUB 등 다양한 형태의 문서를 생성할 수 있습니다.

코드를 문서화하기 위해 sphinx을 이용하여 문서를 생성할 때 필요한 도구를 설치합니다.

make 설치 파일을 다운로드 후 설치합니다.

pip을 이용하여 sphinx를 설치합니다.

> pip3 install sphinx

폴더 하나 생성 후 sphinx-quickstart를 실행하여 기본 설정 파일들을 생성합니다. 다음의 과정을 수행하면 docs 디렉터리에 build, source, make.bat, Makefile이 생성됩니다.

> mkdir docs
docs> cd docs
docs> sphinx-quickstart
Welcome to the Sphinx 6.1.3 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Selected root path: .

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: example
> Author name(s): 2jinu
> Project release []: 1.0.0

If the documents are to be written in a language other than English,
you can select a language here by its language code. Sphinx will then
translate text that it generates into that language.

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

docstring을 인식할 수 있도록 source/conf.py의 로드 경로와 extensions에 sphinx.ext.autodoc요소를 추가해야 합니다.

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

... 생략 ...

extensions = ['sphinx.ext.autodoc']

source/index.rst에서 문서화할 스크립트 파일을 추가합니다.

Welcome to example's documentation!
===================================

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

   mymodule

다음과 같은 디렉터리 구조에서

C:.
├─docs
│   │  make.bat
│   │  Makefile
│   │  mymodule.py
│   │
│   ├─build
│   └─source
│       │  conf.py
│       │  index.rst
│       │
│       ├─_static
│       └─_templates
│
└─mymodule.py

sphinx-apidoc를 이용하여 Python 스크립트에 해당하는 rst를 만들어줍니다.

docs> sphinx-apidoc.exe -o source ..

💡 sphinx-apidoc [OPTIONS] -o <OUTPUT_PATH> <MODULE_PATH> [EXCLUDE_PATTERN …]

이후, make html을 입력하면 build/html에 결과가 생성되며 코드가 수정되거나 다시 명령어를 입력하려면 make clean 이후 다시 html를 만듭니다.

PDF로 변환하기 위해서는 TeXLive 를 설치해야 합니다.

💡 Debian 기반으로 설치하고자 한다면 latexmk, texlive-xetex, texlive-lang을 설치합니다.

이후, make latexpdf를 입력하면 build/latex에 결과가 생성되며 오류 발생 시 conf.py의 language를 en으로 변경하여 실행합니다.

profile
IT 도서관

0개의 댓글