source

가장 일반적인 Python 문서 문자열 형식은 무엇입니까?

bestscript 2023. 1. 16. 20:06

가장 일반적인 Python 문서 문자열 형식은 무엇입니까?

Python에서 docstring을 쓰는 스타일을 몇 가지 봤는데, 가장 인기 있는 스타일은 무엇입니까?

포맷

Python docstring은 다른 게시물과 같이 몇 가지 형식에 따라 작성될 수 있습니다.단, 기본 Sphinx docstring 형식은 언급되지 않았으며 reStructured를 기반으로 합니다.텍스트(reST)블로그 투고에서 주요 형식에 대한 정보를 얻을 수 있습니다.

ReST는 PEP 287에 의해 권장됩니다.

문서 문자열에 사용되는 주요 형식은 다음과 같습니다.

(Epytext)

역사적으로 자바독과 비슷한 스타일이 유행했기 때문에 에피독의 기지로 받아들여졌다.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
"""

- reST

오늘날, 아마도 더 널리 사용되는 형식은 재구조화(reStructured)입니다.문서를 생성하는 데 Sphinx에서 사용되는 텍스트(reST) 형식입니다.주의: 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
"""

- 구글

구글은 종종 사용되는 그들만의 형식을 가지고 있다.스핑크스(즉, 스핑크스)로 해석할 수도 있습니다.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 포맷에 기반한 자체 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
"""

변환/생성 중

Pyment와 같은 도구를 사용하여 아직 문서화되지 않은 Python 프로젝트에 대한 문서 문자열을 자동으로 생성하거나 기존 문서 문자열을 형식에서 다른 형식으로 변환할 수 있습니다.

참고: 예는 Pyment 문서에서 인용한 것입니다.

Google 스타일 가이드에는 뛰어난 Python 스타일 가이드가 포함되어 있습니다.여기에는 PEP-257보다 뛰어난 가이던스를 제공하는 읽기 쉬운 docstring 구문에 대한 표기법이 포함되어 있습니다.예를 들어 다음과 같습니다.

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

Sphinx 설명서 튜토리얼에 설명된 대로 인수에 유형 정보도 포함하도록 이 기능을 확장합니다.예를 들어 다음과 같습니다.

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

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

Docstring 표기법은 PEP-257에 있으며 PEP-8보다 훨씬 상세합니다.

그러나 문서 문자열은 코드의 다른 영역보다 훨씬 개인적인 것으로 보입니다.프로젝트마다 표준이 있습니다.

저는 항상 문서스트링을 포함하는 경향이 있습니다.왜냐하면 문서스트링은 기능의 사용법과 기능을 매우 빠르게 보여주기 때문입니다.

저는 끈의 길이에 상관없이 일관성을 유지하는 것을 선호합니다.움푹 패임과 간격이 일정할 때 모양을 코드화하는 방법을 좋아합니다.즉, 다음을 사용합니다.

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

오버:

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

긴 문서 문자열에서는 첫 번째 줄에 대한 코멘트를 생략하는 경향이 있습니다.

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

이런 식으로 시작하는 의사진행은 지저분하다는 뜻이죠

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

분명히 아무도 그것을 언급하지 않았다: Numpy Docstring Standard를 사용할 수도 있다.그것은 과학계에서 널리 사용되고 있다.

  • 예시와 함께 numpy 형식 지정
  • 렌더링할 sphinx 확장자가 있습니다: numpydoc
  • 또한 렌더링된 문서 문자열이 얼마나 아름다운지 보여주는 예: http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html

Google 스타일의 docstring(@Nathan의 답변에서 권장됨)을 해석하기 위한 Napolean sphinx 확장자 역시 Numpy 스타일의 docstring을 지원하며 두 가지를 간략하게 비교합니다.

마지막으로 기본적인 예를 제시하겠습니다.

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

Python입니다. 든 할 수 있습니다.문서를 게시하는 방법을 고려하십시오.문서 문자열은 소스 코드 판독기 이외에는 표시되지 않습니다.

사람들은 웹에서 문서를 참조하고 검색하는 것을 매우 좋아합니다.이를 위해 문서 도구인 스핑크스를 사용합니다.Python 프로젝트를 문서화하기 위한 사실상의 표준입니다.이 제품은 아름답습니다.https://python-guide.readthedocs.org/en/latest/ 를 봐주세요.Read the Docs(문서 읽기) 웹 사이트에서 무료로 문서를 호스팅합니다.

PEP-257Numpy Docstring Standard에 대한 당신의 문서스트링을 체크하기 위해 Vladimir Keleshev의 pep257 Python 프로그램을 사용하는 것이 좋습니다.

pep257은 표준에서 생성된 차이를 보고하며 pylint 및 pep8이라고 합니다.

언급URL : https://stackoverflow.com/questions/3898572/what-are-the-most-common-python-docstring-formats