programing tip

표준 Python 독 스트링 형식은 무엇입니까?

itbloger 2020. 9. 29. 07:24
반응형

표준 Python 독 스트링 형식은 무엇입니까? [닫은]


파이썬으로 독 스트링을 작성하는 몇 가지 다른 스타일을 보았습니다. 공식적인 또는 "합의 된"스타일이 있습니까?


형식

파이썬 독 스트링은 다른 포스트에서 보여준 것처럼 여러 형식으로 작성할 수 있습니다. 그러나 기본 Sphinx 독 스트링 형식은 언급되지 않았으며 reStructuredText (reST) 기반입니다 . 해당 tuto 에서 주요 형식에 대한 정보를 얻을 수 있습니다 .

reST는 PEP 287에서 권장합니다.

독 스트링에 사용되는 주요 형식은 다음과 같습니다.

-Epytext

역사적으로 javadoc 과 유사한 스타일이 널리 퍼져 있었기 때문에 Epydoc (호출 된 Epytext형식)의 기반으로 문서를 생성했습니다.

예:

"""
This is a javadoc style.

@param param1: this is a first param
@param param2: this is a second param
@return: this is a description of what is returned
@raise keyError: raises an exception
"""

- 쉬다

요즘에는 Sphinx 에서 문서를 생성 하는 데 사용하는 reST ( reStructuredText) 형식이 더 널리 사용되는 형식입니다 . 참고 : JetBrains PyCharm에서 기본적으로 사용됩니다 (메소드를 정의한 후 세 개의 따옴표를 입력하고 Enter 키를 누르십시오). 기본적으로 Pyment의 출력 형식으로도 사용됩니다.

예:

"""
This is a reST style.

:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""

-Google

Google에는 자주 사용되는 자체 형식 이 있습니다. 또한 Sphinx로 해석 할 수 있습니다 (예 : Napoleon 플러그인 사용 ).

예:

"""
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.
"""

심지어 더 많은 예제

-Numpydoc

Numpy 는 Google 형식을 기반으로하고 Sphinx에서 사용할 수있는 자체 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
"""

변환 / 생성

It is possible to use a tool like Pyment to automatically generate docstrings to a Python project not yet documented, or to convert existing docstrings (can be mixing several formats) from a format to an other one.

Note: The examples are taken from the Pyment documentation


The Google style guide contains an excellent Python style guide. It includes conventions for readable docstring syntax that offers better guidance than PEP-257. For example:

def square_root(n):
    """Calculate the square root of a number.

    Args:
        n: the number to get the square root of.
    Returns:
        the square root of n.
    Raises:
        TypeError: if n is not a number.
        ValueError: if n is negative.

    """
    pass

I like to extend this to also include type information in the arguments, as described in this Sphinx documentation tutorial. For example:

def add_value(self, value):
    """Add a new value.

       Args:
           value (str): the value to add.
    """
    pass

Docstring conventions are in PEP-257 with much more detail than PEP-8.

However, docstrings seem to be far more personal than other areas of code. Different projects will have their own standard.

I tend to always include docstrings, because they tend to demonstrate how to use the function and what it does very quickly.

I prefer to keep things consistent, regardless of the length of the string. I like how to code looks when indentation and spacing are consistent. That means, I use:

def sq(n):
    """
    Return the square of n. 
    """
    return n * n

Over:

def sq(n):
    """Returns the square of n."""
    return n * n

And tend to leave off commenting on the first line in longer docstrings:

def sq(n):
    """
    Return the square of n, accepting all numeric types:

    >>> sq(10)
    100

    >>> sq(10.434)
    108.86835599999999

    Raises a TypeError when input is invalid:

    >>> sq(4*'435')
    Traceback (most recent call last):
      ...
    TypeError: can't multiply sequence by non-int of type 'str'

    """
    return n*n

Meaning I find docstrings that start like this to be messy.

def sq(n):
    """Return the squared result. 
    ...

As apparantly no one mentioned it: you can also use the Numpy Docstring Standard. It is widely used in the scientific community.

The Napolean sphinx extension to parse Google-style docstrings (recommended in the answer of @Nathan) also supports Numpy-style docstring, and makes a short comparison of both.

And last a basic example to give an idea how it looks like:

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

    Extended description of function.

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

    Returns
    -------
    bool
        Description of return value

    See Also
    --------
    otherfunc : some related other function

    Examples
    --------
    These are written in doctest format, and should illustrate how to
    use the function.

    >>> a=[1,2,3]
    >>> print [x + 3 for x in a]
    [4, 5, 6]
    """
    return True

PEP-8 is the official python coding standard. It contains a section on docstrings, which refers to PEP-257 -- a complete specification for docstrings.


It's Python; anything goes. Consider how to publish your documentation. Docstrings are invisible except to readers of your source code.

People really like to browse and search documentation on the web. To achieve that, use the documentation tool Sphinx. It's the de-facto standard for documenting Python projects. The product is beautiful - take a look at https://python-guide.readthedocs.org/en/latest/ . The website Read the Docs will host your docs for free.


I suggest using Vladimir Keleshev's pep257 Python program to check your docstrings against PEP-257 and the Numpy Docstring Standard for describing parameters, returns, etc.

pep257 will report divergence you make from the standard and is called like pylint and pep8.

참고URL : https://stackoverflow.com/questions/3898572/what-is-the-standard-python-docstring-format

반응형