Python Docstring

From GM-RKB
Jump to navigation Jump to search

A Python Docstring is a Docstring that is used within Python language code to document a specific segment of Python code.

  • Context:
    • It can (typically) include a description of the function, module, class, or script it documents, including its parameters, return values, and any exceptions that it raises.
    • It can (often) be accessed programmatically at runtime, which allows for the dynamic generation of documentation or usage guides directly from the code.
    • It can be used to document Functions, Classes, Modules, and Scripts within Python applications.
    • It can serve as an integral part of Automatic Documentation Generation tools, such as Sphinx, by providing the necessary metadata to generate comprehensive documentation automatically.
    • It is enclosed in triple quotes (either or """), allowing for multiline string literals that facilitate comprehensive documentation directly adjacent to the code segment it describes.
    • It can follow specific conventions and formatting guidelines, such as those outlined in PEP 257, to enhance readability and utility for other developers.
    • It can include doctest strings, which are a form of Test-Driven Development in Python, where examples included within the docstring can be tested to ensure they produce the expected output.
    • It is recommended by Python's official style guide, PEP 8, to maintain consistency and readability in Python codebases.
    • ...
  • Example(s):
    • A simple Python docstring for a function might look like this:
      • def add(a, b):
        """
        Add two numbers and return the result.

        Parameters:
        a (int): The first number.
        b (int): The second number.

        Returns:
        int: The sum of a and b.
        """
        return a + b
    • For a Python class, the docstring might document its purpose, its methods, and their respective functionalities:
      • class MathOperations:
        """
        This class offers basic mathematical operations.

        Methods:
        add(a, b) -- Returns the sum of two numbers.
        subtract(a, b) -- Returns the difference between two numbers.
        """
        def add(self, a, b):
        return a + b

        def subtract(self, a, b):
        return a - b
    • ...
  • Counter-Example(s):
    • Inline comments in Python using the # symbol, which are intended for brief explanations or notes to the developer and are not accessible programmatically.
    • Block comments in languages like C or Java, where documentation is not embedded within the source code as string literals and cannot be accessed at runtime.
  • See: Docstring, Comment (Computer Programming), PEP 257, Sphinx (Documentation Generator).