docstring

docstring 이란

  • python class, function, attributes에 대한 설명

  • 아래는 pickle 객체에 대한 docstring 이며, docstring이 있는 경우 __doc__ 속성으로 접근 가능

  • docstring을 이용하여 api 문서 자동화(sphinx)를 할 수 있고

  • 개발자간 협업을 위해서는 docstring을 잘 정리해야 함

import pickle
import pandas as pd
print(pickle.__doc__)
# print(pd.read_csv.__doc__)
Create portable serialized representations of Python objects.

See module copyreg for a mechanism for registering custom picklers.
See module pickletools source for extensive comments.

Classes:

    Pickler
    Unpickler

Functions:

    dump(object, file)
    dumps(object) -> string
    load(file) -> object
    loads(bytes) -> object

Misc variables:

    __version__
    format_version
    compatible_formats

docstring syntax

inline docstring

def square(n):
    ''' Takes in a number n, returns the square of n'''
    return n**2
print(square.__doc__)
 Takes in a number n, returns the square of n

multline docstring

def add_binary(a, b):
    '''
    Returns the sum of two decimal numbers in binary digits.

            Parameters:
                    a (int): A decimal integer
                    b (int): Another decimal integer

            Returns:
                    binary_sum (str): Binary string of the sum of a and b
    '''
    binary_sum = bin(a+b)[2:]
    return binary_sum
print(add_binary.__doc__)
    Returns the sum of two decimal numbers in binary digits.

            Parameters:
                    a (int): A decimal integer
                    b (int): Another decimal integer

            Returns:
                    binary_sum (str): Binary string of the sum of a and b
    

docstring style

  1. sphinx style: python documentation style

  2. google style: simple

sphinx style

class Vehicle(object):
    '''
    The Vehicle object contains lots of vehicles
    :param arg: The arg is used for ...
    :type arg: str
    :param `*args`: The variable arguments are used for ...
    :param `**kwargs`: The keyword arguments are used for ...
    :ivar arg: This is where we store arg
    :vartype arg: str
    '''


    def __init__(self, arg, *args, **kwargs):
        self.arg = arg

google style

class Vehicles(object):
    '''
    The Vehicle object contains a lot of vehicles

    Args:
        arg (str): The arg is used for...
        *args: The variable arguments are used for...
        **kwargs: The keyword arguments are used for...

    Attributes:
        arg (str): This is where we store arg,
    '''
    def __init__(self, arg, *args, **kwargs):
        self.arg = arg

jupyter notebook output format 정의

  • jupyter notebook output을 markdown 형태로 출력

from IPython.display import display, Markdown
display(Markdown('**_some_ markdown** and an [internal reference](render/output/markdown)!'))

some markdown and an internal reference!