Programing

파라미터로 메소드를 문서화하는 방법은 무엇입니까?

lottogame 2020. 7. 14. 08:17
반응형

파라미터로 메소드를 문서화하는 방법은 무엇입니까?


파이썬의 문서 문자열을 사용하여 매개 변수로 메소드를 문서화하는 방법은 무엇입니까?

편집 : PEP 257 은 다음 예제를 제공합니다.

def complex(real=0.0, imag=0.0):
    """Form a complex number.

    Keyword arguments:
    real -- the real part (default 0.0)
    imag -- the imaginary part (default 0.0)

    """
    if imag == 0.0 and real == 0.0: return complex_zero
    ...

이것은 대부분의 파이썬 개발자들이 사용하는 규칙입니까?

Keyword arguments:
<parameter name> -- Definition (default value if any)

나는 좀 더 공식적인 것을 기대하고 있었다

def complex(real=0.0, imag=0.0):
    """Form a complex number.

    @param: real The real part (default 0.0)
    @param: imag The imaginary part (default 0.0)

    """
    if imag == 0.0 and real == 0.0: return complex_zero
    ...

환경 : Python 2.7.1


내 경험을 바탕으로, NumPy와 문서화 문자열 규칙은 (PEP257 상위) 가장 널리 확산되어 다음 또한 다음과 같은 도구가 지원하는 규칙 스핑크스 .

한 가지 예 :

Parameters
----------
x : type
    Description of parameter `x`.

docstring은 자유 형식이므로 코드를 구문 분석하여 API 문서를 생성하는 데 사용하는 내용에 따라 달라집니다.

나는 익숙해 추천 할 것입니다 스핑크스 마크 업 이 널리 이용되고 있기 때문에 우수한 부분적으로, 파이썬 프로젝트를 문서화하기위한 사실상의 표준이되고 있기 때문에, readthedocs.org의 서비스를 제공합니다. Sphinx 문서 의 예제 를 파이썬 스 니펫으로 바꾸어 표현 하려면 :

def send_message(sender, recipient, message_body, priority=1):
   '''
   Send a message to a recipient

   :param str sender: The person sending the message
   :param str recipient: The recipient of the message
   :param str message_body: The body of the message
   :param priority: The priority of the message, can be a number 1-5
   :type priority: integer or None
   :return: the message id
   :rtype: int
   :raises ValueError: if the message_body exceeds 160 characters
   :raises TypeError: if the message_body is not a basestring
   '''

이 마크 업은 문서와 기타 문서 간의 상호 참조지원합니다 . 스핑크스 문서는 (예를 들어)를 사용 :py:attr:하지만 :attr:소스 코드에서 문서화 할 때만 사용할 수 있습니다 .

당연히 API를 문서화하는 다른 도구가 있습니다. 명령 을 사용 하는 더 고전적인 Doxygen있지만 Sphinx와 같은 Python 코드를 문서화하도록 특별히 설계되지 않았습니다.\param

Note that there is a similar question with a similar answer in here...


Conventions:

Tools:


Update: Since Python 3.5 you can use type hints which is a compact, machine-readable syntax:

from typing import Dict, Union

def foo(i: int, d: Dict[str, Union[str, int]]) -> int:
    """
    Explanation: this function takes two arguments: `i` and `d`.
    `i` is annotated simply as `int`. `d` is a dictionary with `str` keys
    and values that can be either `str` or `int`.

    The return type is `int`.

    """

The main advantage of this syntax is that it is defined by the language and that it's unambiguous, so tools like PyCharm can easily take advantage from it.


python doc strings are free-form, you can document it in any way you like.

Examples:

def mymethod(self, foo, bars):
    """
    Does neat stuff!
    Parameters:
      foo - a foo of type FooType to bar with.
      bars - The list of bars
    """

Now, there are some conventions, but python doesn't enforce any of them. Some projects have their own conventions. Some tools to work with docstrings also follow specific conventions.


If you plan to use Sphinx to document your code, it is capable of producing nicely formatted HTML docs for your parameters with their 'signatures' feature. http://sphinx-doc.org/domains.html#signatures


The mainstream is, as other answers here already pointed out, probably going with the Sphinx way so that you can use Sphinx to generate those fancy documents later.

That being said, I personally go with inline comment style occasionally.

def complex(  # Form a complex number
        real=0.0,  # the real part (default 0.0)
        imag=0.0  # the imaginary part (default 0.0)
        ):  # Returns a complex number.
    """Form a complex number.

    I may still use the mainstream docstring notation,
    if I foresee a need to use some other tools
    to generate an HTML online doc later
    """
    if imag == 0.0 and real == 0.0:
        return complex_zero
    other_code()

One more example here, with some tiny details documented inline:

def foo(  # Note that how I use the parenthesis rather than backslash "\"
          # to natually break the function definition into multiple lines.
        a_very_long_parameter_name,
            # The "inline" text does not really have to be at same line,
            # when your parameter name is very long.
            # Besides, you can use this way to have multiple lines doc too.
            # The one extra level indentation here natually matches the
            # original Python indentation style.
            #
            # This parameter represents blah blah
            # blah blah
            # blah blah
        param_b,  # Some description about parameter B.
            # Some more description about parameter B.
            # As you probably noticed, the vertical alignment of pound sign
            # is less a concern IMHO, as long as your docs are intuitively
            # readable.
        last_param,  # As a side note, you can use an optional comma for
                     # your last parameter, as you can do in multi-line list
                     # or dict declaration.
        ):  # So this ending parenthesis occupying its own line provides a
            # perfect chance to use inline doc to document the return value,
            # despite of its unhappy face appearance. :)
    pass

The benefits (as @mark-horvath already pointed out in another comment) are:

  • Most importantly, parameters and their doc always stay together, which brings the following benefits:
  • Less typing (no need to repeat variable name)
  • Easier maintenance upon changing/removing variable. There will never be some orphan parameter doc paragraph after you rename some parameter.
  • and easier to find missing comment.

Now, some may think this style looks "ugly". But I would say "ugly" is a subjective word. A more neutual way is to say, this style is not mainstream so it may look less familiar to you, thus less comfortable. Again, "comfortable" is also a subjective word. But the point is, all the benefits described above are objective. You can not achieve them if you follow the standard way.

Hopefully some day in the future, there will be a doc generator tool which can also consume such inline style. That will drive the adoption.

PS: This answer is derived from my own preference of using inline comments whenever I see fit. I use the same inline style to document a dictionary too.


Docstrings are only useful within interactive environments, e.g. the Python shell. When documenting objects that are not going to be used interactively (e.g. internal objects, framework callbacks), you might as well use regular comments. Here’s a style I use for hanging indented comments off items, each on their own line, so you know that the comment is applying to:

def Recomputate \
  (
    TheRotaryGyrator,
      # the rotary gyrator to operate on
    Computrons,
      # the computrons to perform the recomputation with
    Forthwith,
      # whether to recomputate forthwith or at one's leisure
  ) :
  # recomputates the specified rotary gyrator with
  # the desired computrons.
  ...
#end Recomputate

You can’t do this sort of thing with docstrings.

참고URL : https://stackoverflow.com/questions/9195455/how-to-document-a-method-with-parameters

반응형