본문 바로가기

프로그래밍/python

[python] Docstrings(String Literal)

Docstring(Documentation String)이란, 모듈, 함수, 클래스 또는 메서드 정의의 가장 첫 번째 줄에 선언된 문자열 리터럴(String Literal)을 의미합니다.

일반적인 주석(Comment, #)이 코드가 '어떻게(How)' 작동하는지 구현 원리를 메모하는 용도라면, Docstring은 이 함수가 '무엇을(What)' 하는지, 어떤 파라미터를 받고 무엇을 반환하는지를 설명하는 역할을 합니다. 

 

Function's docstrings 
def get_name(first_name, last_name):
    '''take first name and last name then return combine two'''
    if first_name == "":
        return "Your first name is missing ..."
    if last_name == "":
        return "Your last name is missing ..."
    return f"{first_name}, {last_name}"
  • function invoke 할 때, 함수에 대한 설명으로 사용됨.
    • get_name() 사용 시 자동으로 표시
    • print(get_name.__doc__) : docstring 내용 출력
  • 작은따옴표(') 혹은 큰 따옴표(") 사용
    • """<docstring>"""
    • '''<docstring>''' 
Docstring Style 1 - Google
# - Google
"""
This is an example of Google style.

Args:
    param1: This is the first param.
    param2: This is a second param.

Returns:
    This is a description of what is returned.

Raises:
    KeyError: Raises an exception.
"""
  • Python에서 가장 추천되는 방식
  • 기능요약(Summary), 매개변수(Args), 반환값(Returns), 예외(Raises)의 순서로 작성
  • 핵심 규칙: 각 섹션 제목(Args:, Returns:, Raises:) 아래 내용은 반드시 들여 쓰기(Indent)를 하여 종속됨을 표현
Docstring Style 1 - Numpydoc
"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.

Parameters
----------
first : array_like
    the 1st param name `first`
second :
    the 2nd param
third : {'value', 'other'}, optional
    the 3rd param, by default 'value'

Returns
-------
string
    a value in a string

Raises
------
KeyError
    when a key error
OtherError
    when an other error
"""
  • NumPy, SciPy, Pandas 등 데이터 과학 생태계에서 표준으로 사용하는 방식
  • 방식 : 밑줄(Underline)을 통한 명확한 구획과 타입(Type) 중심의 기술
    • 기능 요약 (Summary)  -> [맨 첫 줄]
      • 간략한 요약(한 줄)
      • 상세한 설명(여러줄) 
    • Parameters (매개변수) -> [변수명 : 타입]
      • 변수명 뒤에 콜론(:)과 데이터 타입을 명시
      • 설명은 다음 줄 들여쓰기 후 
    • Returns (반환값) -> [타입 (이름 : 타입)]
      • 반환값의 자료형(Type)을 먼저 강조하여 적고,
      • 그 아래 줄에 해당 값의 의미를 설명
    • Raises (예외) -> [에러명]
      • 발생 가능한 예외 클래스 이름을 적고,
      • 그 아래 줄에 언제 발생하는지 조건을 설명

-------------------------------------------------------------------------------

참고 : 실리콘밸리 엔지니어가 가르치는 파이썬 기초부터 고급까지 (inflearn, 미쿡엔지니어) 

-------------------------------------------------------------------------------