본문 바로가기

Python

[Clean Python] Docsting 사용하기

1. Python에서의 Docstring

파이썬에서 코드를 문서화하는 강력한 방법이 바로 Docstring이다. docstring은 해당 객체의 __doc__ 특수 속성이 된다.
공식 언어에서는 docstring을 작성하기 위해 """삼중 큰따옴표(Quotes Marks)"""를 사용하는 것을 권장한다.
이와 관련된 모범 사례를 살펴보자.

독스트링을 작성하는 방법은 여러가지가 있지만 파이씬의 정의한 몇 가지의 공통 규칙은 다음과 같다.

- 문자열이 한 라인에 있어도 triple quotes(삼중 큰따옴표)가 사용된다.
- triple quotes의 문자열 전후에 빈 라인이 없어야한다.
- period(.)를 사용해 docstring에서 구문을 종료한다.


마찬가지로 파이썬 multiline docstring 규칙을 적용해서 문서화할 수 있다.

## 멀티라인 독스트링 예시
def call_weather_api(url, location):
    """Get the weather of specific location.

    Calling weather api to check for weather by using weather api and location.
    Make sure you provice city name only, country and county names won't be accepted
    and will throw exception if not found the city name.

    :param url:  URL of the api to get weather.
    :type url: str
    :param location:  Location of the city to get the weather.
    :type location: str
    :return: Give the weather information of given location.
    :rtype: str
    """
    pass


위 예시에서 주목해야 할 몇 가지 사항이 있다.

- 첫 번째 라인은 함수나 클래스에 대한 간략한 설명이다.
- 라인의 끝 부분에 마침표가 있다.
- 간단한 설명과 docstring의 요약 사이에 한 라인의 간격이 있다.


다음으로 두 번째 예시는 type을 사용하는 케이스이다. 이때는 매개변수 정보를 작성할 필요가 없다.

## type을 사용하는 경우 
def call_weather_api(url: str, location: str) -> str:
    """Get the weather of specific location.

    Calling weather api to check for weather by using weather api and location.
    Make sure you provice city name only, country and county names won't be
    accepted and will throw exception if not found the city name.
    """
    pass

위에서 말한 내용들은 docstring을 사용할 때 파이썬이 권장하는 방식이고, 이 부분에 대한 정답은 없다. 하지만 프로젝트 전반에서docstring에 대해 동일한 스타일을 사용해야 일관된 형식을 유지할 수 있다는 것이 가장 중요하다.


Google의 Docstring 예시

""주어진 url을 호출한다.

Parameters:
    url (str): 호출 url 주소

Returns:
    dict: url api 응답
"""


공식 파이썬 문서에서 권장하는 Docstring 예시

""" 주어진 url을 호출한다.

:param url: 호출 url
:type url: str
:returns: url api 응답
:rtype: dict
"""

2. 모듈 레벨 독스트링(Module-level-Docstring)

모듈의 사용법을 간력히 설명하기 위해 파일의 맨 위에 Module-level Dicstring을 위치시킨다.
이 독스트링은 특정 메소드나 클래스에 대해 말하는 것이 아니라 모듈의 모든 메소드/클래스를 포함해 모듈의 목표를 살펴보아야한다.

"""This module contains all the network related request.

This module will check for all the exceptions while making the network calls
and raise exceptions for any unknown exception. Make sure that when you use
this module, you handle these exceptions in client code as:
        NetworkError exception for network calls.
        NetworkNotFound exception if network not found.
"""


import urllib3
import json


모듈을 위한 독스트링을 작성할 때 고려해야할 사항은 다음과 같다.

- 모듈의 목적에 대한 간단할 설명을 작성한다.
- 위 예시처럼 모듈에 대해 알아야할 정보를 확인하기 위한 예외 정보를 추가할 수는 있으나, 너무 자세하게는 다루지 말자.
- 모든 함수 또는 클래스 연산의 세부 사항을 살펴보지 않고, 모듈의 설명 정보를 제공하는 방법으로 작성하는 것을 고려하자.

3. 클래스 독스트링

Class 독스트링은 주로 클래스의 사용과 전체적인 목표를 간략하게 설명하는데 사용한다.
만약 멀티라인이라면 클래스의 사용법과 예시를 작성할 수 있다.

## 클래스 멀티라인 독스트링 예시
class Student:
    """Student class information.

    This class handle actions performed by a student.
    This class provides information about student full name, age, roll-number and  other information.

    Usage:
    import student

    student = student.Student()
    student.get_name()
    >>> 678998
    """

    def __init__(self):
        pass

 

4. 함수 독스트링

함수 독스트링은 함수의 맨 위에 작성하며, 주로 함수의 연산에 대해 설명한다. 만약 typing을 사용하지 않는 경우, 아래 예시처럼 매개변수를 참고하는 것을 고려한다.

## 함수 독스트링 예시
def is_prime_number(number):
    """Check for prime number.

    Check the given number is prime number or not by checking against all the
    numbers less the square root of given number.

    :param number:  Given number to check for prime.
    :type number: int
    :return: True if number is prime otherwise False.
    :rtype: boolean
    """
    pass



Reference : Sunil Kapil | Clean Python: Elegant Coding in Python