파이썬 Docstring 작성법
파이썬에서 함수 혹은 클래스를 정의할 때 코드 그 자체만으로 의도가 분명히 드러나는 코드가 사실상 가장 훌륭한 코드이다. 하지만 어떤 때에는 키워드 매개변수들에 어떤 값을 넣어야 하며, 기본값이 존재하는지의 여부와 함수의 인풋과 아웃풋을 명확하게 표시하기 위해 문서화를 하는 것도 중요하다.
파이썬은 기본적으로 문서화를 위해 독스트링(docstring) 기능을 제공한다. 해당 독스트링을 통해 사용자에게 기능을 사용함에 있어 편의성을 제공할 수 있다. 독스트링은 어떻게 작성하며, 어떻게 불러올 수 있는지 파이썬 PEP 문서를 보고 간단히 알아보았다.
https://peps.python.org/pep-0257/
PEP 257 – Docstring Conventions | peps.python.org
PEP 257 – Docstring Conventions Author: David Goodger , Guido van Rossum Discussions-To: Doc-SIG list Status: Active Type: Informational Created: 29-May-2001 Post-History: 13-Jun-2001 Table of Contents This PEP documents the semantics and conventions ass
peps.python.org
One-Line Docstring
one-line docstring은 말 그대로 한 줄에 간단하게 함수의 목적을 드러내는 독스트링이다.
def square(a):
'''Returned argument a is squared.'''
return a**a
- 큰 따옴표 혹은 작은따옴표 세 개로 한 줄에서 열고 닫는다.
- 독스트링의 앞 뒤로 빈칸을 두지 않는다.
Multi-Line Docstring
multi-line docstring 또한 말 그대로 여러 줄로 되어 좀 더 자세한 정보를 제공하는 독스트링이다.
def some_function(argument1):
"""Summary or Description of the Function
Parameters:
argument1 (int): Description of arg1
Returns:
int:Returning value
"""
return argument1
예시와 같이 함수의 기능에 대한 간략한 설명에 더해 매개변수와 반환 값에 대한 정보가 추가된다.
그리고 위와 같이 한 줄 혹은 여러 줄로 작성된 독스트링을 불러올 때는 매직 메서드인 "__doc__"을 사용하여 불러올 수 있다.
>>> some_function.__doc__
Summary or Description of the Function
Parameters:
argument1 (int): Description of arg1
Returns:
int:Returning value
독스트링을 작성하는 다양한 스타일
독스트링을 작성하는 방법에 대해 간단하게 알아보았는데, 좀 더 명확하게 어떤 컨벤션이 존재하지 않을 까란 생각이 들었다. 아래 Stackoverflow 링크를 따라가면 다양한 스타일들에 대한 정보가 존재하니 참조하기 바란다.
https://stackoverflow.com/questions/3898572/what-are-the-most-common-python-docstring-formats
What are the most common Python docstring formats?
I have seen a few different styles of writing docstrings in Python, what are the most popular styles?
stackoverflow.com