문서화

../_images/35620636012_f66aa88f93_k_d.jpg

가독성은 파이썬 개발자의 기본적인 관심사입니다. 이는 프로젝트와 코드 문서화 모두 해당됩니다. 몇 가지 간단한 우수 사례를 따라해봅시다. 당신 뿐 아니라 다른 모두의 시간을 절약해줄 것입니다.

프로젝트 문서화

최상위 디렉토리의 README 파일에는 해당 프로젝트의 사용자와 유지보수 담당자 모두에게 도움이 되는 일반적인 정보가 있어야 합니다. 순수한 텍스트로 작성하시거나, 읽기 아주 쉬운 마크업 문서로 작성하세요. reStructuredText 나 마크다운 같은 것이면 됩니다. 여기에는 반드시 프로젝트나 라이브러리(사용자가 이 프로젝트의 모든 것을 알고 있을거라고 생각하면 안됩니다)의 목적을 설명하는 몇 줄의 글, 소프트웨어를 위한 주요 소스의 URL, 몇 가지 기본적인 신용 정보를 포함해야 합니다.

An INSTALL file is less necessary with Python. The installation instructions are often reduced to one command, such as pip install module or python setup.py install, and added to the README file.

LICENSE 파일은 반드시 있어야만 합니다. 그리고 소프트웨어가 공개 가능한지 여부를 명시하는 라이선스를 명시해야 합니다.

README 안의 TODO 파일이나 TODO 섹션에는 개발할 코드의 목록을 나열해야 합니다.

CHANGELOG 파일이나 README 안의 섹션에는 반드시 최신 버전의 코드에서 일어난 변화에 대하여 개략적인 소개가 있어야 합니다.

프로젝트 발표

프로젝트에 따라서 당신의 문서는 아래의 것들 중 몇 개를 포함하거나, 혹은 전부를 포함할 것입니다.

  • An introduction should give a very short overview of what can be done with the product, using one or two extremely simplified use cases. This is the thirty-second pitch for your project.
  • 튜토리얼(tutorial) 은 몇 가지 기본적인 유즈케이스를 좀 더 자세히 보여주어야 합니다. 읽는 이는 하나 하나씩 따라가며 실제 동작하는 프로토타입을 만들 것입니다.
  • API 레퍼런스(reference) 는 보통 코드에서 생성됩니다(docstrings 를 보세요). 공개적으로 가능한 모든 인터페이스, 파라미터, 리턴값을 보여주어야 합니다.
  • 개발자 문서(Developer documentation) 는 잠재적인 기여자(contributors)를 위한 것입니다. 여기에는 코딩 규약(code convention)과 프로젝트의 일반적인 디자인 전략을 담을 수 있습니다.

스핑크스(Sphinx)

Sphinx 는 단연코 가장 유명한 파이썬 문서화 도구입니다. 쓰세요.reStructuredText 마크업 언어를 HTML, LaTeX(인쇄 가능한 PDF 버전), 매뉴얼 페이지, 일반 텍스트 등의 포맷으로 바꿔줍니다.

뿐만 아니라 Sphinx 문서를 위한 훌륭하면서도, 무료인 호스팅 서비스가 있습니다: Read The Docs 입니다. 쓰세요. 소스 저장소에 커밋 후크를 걸어두면 문서를 자동으로 빌드하도록 설정할 수 있습니다.

When run, Sphinx will import your code and using Python's introspection features it will extract all function, method, and class signatures. It will also extract the accompanying docstrings, and compile it all into well structured and easily readable documentation for your project.

주석

Sphinx는 API 생성기로도 유명하지만, 일반적인 프로젝트 문서화로도 잘 작동합니다. 이 안내서는 Sphinx 로 빌드되었고, Read The Docs 로 호스팅되었습니다.

reStructuredText

Most Python documentation is written with reStructuredText. It's like Markdown, but with all the optional extensions built in.

reStructuredText PrimerreStructuredText Quick Reference 가reStructuredText의 문법에 익숙해지는데 큰 도움을 줄 것입니다.

코드 문서에 대한 조언

주석은 코드를 명확하게 합니다. 그리고 코드를 이해하기 쉽도록 하고자 덧붙여집니다. 파이썬에서는 주석이 해시 (숫자 표시) (#)로 시작됩니다.

파이썬에서는 독스트링(docstrings) 이 모듈, 클래스, 함수를 설명합니다.

def square_and_rooter(x):
    """Return the square root of self times self."""
    ...

보통 PEP 8#comments (the "파이썬 스타일 안내서(Python Style Guide)")의 주석 섹션대로 따라하시면 됩니다. PEP 0257#specification (The Docstring Conventions Guide)에서 독스트링에 대한 더 많은 정보를 볼 수 있습니다.

코드를 주석 처리하기

세따옴표를 코드의 주석 처리에 쓰지 마세요. 좋은 습관이 아닙니다. grep처럼 라인 기반 커맨드 라인 도구는 주석 처리된 코드가 비활성화되었는지를 인식하지 못합니다. 주석 처리할 모든 줄의 적당히 들여쓴 위치에다 해시를 붙이는 편이 좋습니다. 에디터에 이런 작업을 쉽게 해주는 기능이 있을 것입니다. 주석 처리/해제하는 단축키를 배울 필요가 있습니다.

독스트링(Docstrings)과 마법

어떤 도구는 단위 테스트 로직처럼 문서 이상의 동작을 시키기 위해 독스트링을 이용합니다. 이런 도구들은 멋지지만, 절대 고장나지 않습니다. "이렇게 동작할거야." 같은 역할을 할 뿐입니다.

Sphinx 같은 툴은 당신의 독스트링을 reStructuredText로 파싱해서 HTML로 정확히 만들어줍니다. 이 방법은 프로젝트 문서에 예제 코드의 스니펫을 아주 간단히 집어넣을 수 있도록 해줍니다.

Additionally, Doctest will read all embedded docstrings that look like input from the Python commandline (prefixed with ">>>") and run them, checking to see if the output of the command matches the text on the following line. This allows developers to embed real examples and usage of functions alongside their source code. As a side effect, it also ensures that their code is tested and works.

def my_function(a, b):
    """
    >>> my_function(2, 3)
    6
    >>> my_function('a', 3)
    'aaa'
    """
    return a * b

독스트링(Docstrings) 대 블록 주석

독스트링(Docstrings)과 블록 주석은 서로 바꿔쓸 수 없습니다. 함수나 클래스에서 맨 앞줄의 주석 블록은 개발자의 메모로 쓰입니다. 독스트링은 함수나 클래스의 동작 을 나타냅니다.

# This function slows down program execution for some reason.
def square_and_rooter(x):
    """Returns the square root of self times self."""
    ...

Unlike block comments, docstrings are built into the Python language itself. This means you can use all of Python's powerful introspection capabilities to access docstrings at runtime, compared with comments which are optimized out. Docstrings are accessible from both the __doc__ dunder attribute for almost every Python object, as well as with the built in help() function.

While block comments are usually used to explain what a section of code is doing, or the specifics of an algorithm, docstrings are more intended towards explaining other users of your code (or you in 6 months time) how a particular function can be used and the general purpose of a function, class, or module.

독스트링(Docstrings) 작성

작성한 함수, 메서드, 클래스가 얼마나 복잡한지에 따라 다르겠지만 단 1줄의 독스트링이 가장 적절할 것입니다. 다음은 흔히 쓰이면서도 아주 분명한 예시입니다:

def add(a, b):
    """Add two numbers and return the result."""
    return a + b

독스트링은 이해하기 쉬운 방법으로 함수를 설명해야 합니다. 별 것도 아닌 함수나 클래스나 간단한 함수 구문(예를 들면 add(a, b) -> result) 에서는 독스트링이 필요하지 않습니다. 파이썬의 inspect 모듈이 이미 있기에 필요시 아주 빠르게 원하는 정보를 찾을 수 있고 소스 코드도 손쉽게 읽을 수 있기 때문입니다.

하지만 더 크고 복잡한 프로젝트라면 함수 정보, 이게 뭘 하는지, 어떤 예외를 발생시키는지, 무엇을 반환하는지, 파라미터에 관한 연관 정보에 대하여 더 많이 설명하는 편이 좋은 경우도 많습니다.

For more detailed documentation of code a popular style used, is the one used by the NumPy project, often called NumPy style docstrings. While it can take up more lines than the previous example, it allows the developer to include a lot more information about a method, function, or class.

def random_number_generator(arg1, arg2):
    """
    Summary line.

    Extended description of function.

    Parameters
    ----------
    arg1 : int
        Description of arg1
    arg2 : str
        Description of arg2

    Returns
    -------
    int
        Description of return value

    """
    return 42

스핑크스에 sphinx.ext.napoleon 플러그인을 추가하면 이러한 스타일의 독스트링을 파싱하여 NumPy 스타일의 독스트링을 당신의 프로젝트에 집어넣기 쉽게 해줍니다.

At the end of the day, it doesn't really matter what style is used for writing docstrings; their purpose is to serve as documentation for anyone who may need to read or make changes to your code. As long as it is correct, understandable, and gets the relevant points across then it has done the job it was designed to do.

독스트링에 대하여 더 많이 읽고 싶다면 가벼운 마음으로 PEP 257 와 상의하세요.

다른 도구

황야에 외롭게 서 있는 도구들도 있습니다. 그냥 스핑크스(Sphinx) 쓰세요.

Pycco
Pycco는 "문학적 프로그래밍 스타일의 문서 생성기" 이자, node.js Docco 의 파이썬 포팅입니다. 코드를 HTML 코드와 문서가 나란히 있는 모습으로 만들어줍니다.
Ronn
Ronn은 유닉스 매뉴얼을 빌드합니다. 사람이 읽을 수 있는 텍스트 파일을 roff로 변환하여 터미널에서 보여줄 수 있을 뿐만 아니라 웹을 위해 HTML로도 바꿔줍니다.
Epydoc
Epydoc은 끝장났습니다. 대신 스핑크스(Sphinx) 를 쓰세요.
MkDocs
MkDocs은 마크다운으로 프로젝트 문서를 빌드하기 위하여 설계된 빠르고 단순한 정적 사이트 생성기입니다.