1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Do I need to declare types? Documenting public class fields and enum values?

Discussão em 'Python' iniciado por Stack, Setembro 15, 2024.

  1. Stack

    Stack Membro Participativo

    I would like to add API docs to my Python project. I've chosen the reStructuredText standard, as it is supported out of the box by PyCharm. Here are my questions:


    1. When describing function parameters (args) and the returned value, should I include their types? Even if they are already included in function signature? I.e.:

      # A1 - NO TYPES IN DOCSTRING
      def cuckoo(key: str, value: int) -> dict:
      """Do stuff.

      :param key: The precious key
      :param value: The valuable value
      :returns: The feedback wrapped in a dictionary
      """
      return {key: (value + 6) * 1024}


      # A2 - TYPES VIA :TYPE: AND :RTYPE:
      def cuckoo(key: str, value: int) -> dict:
      """Do stuff.

      :param key: The precious key
      :type key: str
      :param value: The valuable value
      :type value: int
      :returns: The feedback wrapped in a dictionary
      :rtype: dict
      """
      return {key: (value + 6) * 1024}


      # A3 - TYPES INSIDE :pARAM: AND :RETURNS:
      def cuckoo(key: str, value: int) -> dict:
      """Do stuff.

      :param str key: The precious key
      :param int value: The valuable value
      :returns dict: The feedback wrapped in a dictionary
      """
      return {key: (value + 6) * 1024}

    2. How should I document public class fields? I've seen 2 conventions (the latter looking ugly and counter intuitive):

      # B1 - VIA CLASS PARAM
      @dataclass
      class Person:
      """Represents a physical person.

      :param id: Unique identifier
      :param first_name: Their first name
      :param last_name: Their current surname
      """
      id: int
      first_name: str
      last_name: str


      # B2 - VIA #:
      @dataclass
      class Person:
      """Represents a physical person."""
      #: Unique identifier
      id: int
      #: Their first name
      first_name: str
      #: Their current surname
      last_name: str

    3. Is this the correct way of documenting different Enum values?

      class MyStatus(Enum):
      """The final status of our operation."""

      SUCCESS = auto()
      """A great success!"""
      FAILURE = auto()
      """Something has gone terribly wrong."""
      TIMEOUT = auto()
      """It was taking too long, so we've decided to cancel the whole thing."""

    Continue reading...

Compartilhe esta Página