杰瑞科技汇

format python doc 如何规范使用?

Of course! Here is a comprehensive guide to formatting Python docstrings, following the most common and recommended standards.

format python doc 如何规范使用?-图1
(图片来源网络,侵删)

The Golden Rule: Consistency is Key

The most important rule for documentation is to be consistent. Choose one style and stick with it throughout your project.

The most widely used styles are:

  1. Google Style (Recommended for its clarity and readability)
  2. reStructuredText (reST) / Sphinx Style (The traditional standard for large projects, especially those using Sphinx for docs generation)
  3. NumPy/SciPy Style (A very detailed style popular in the scientific Python community)

We'll focus on Google Style as it's modern, easy to read, and the default for many tools, including PyCharm and VS Code's built-in docstring generators.


Google Style Docstrings (Recommended)

This style is known for its simplicity and human-friendly format. It uses sections marked by a line with a single word followed by a colon.

format python doc 如何规范使用?-图2
(图片来源网络,侵删)

Basic Structure

A Google-style docstring has the following components, all optional except for the summary:

"""[Summary line]
[Body paragraph. Can span multiple lines.]
Args:
    [Argument Name] ([Type]): [Description of the argument].
Returns:
    [Type]: [Description of the return value].
Raises:
    [ErrorType]: [Description of the error being raised].
"""
# Example:
def fetch_user_data(user_id: int) -> dict:
    """Fetches user data from the database.
    This function connects to the primary database and retrieves the profile
    information for the given user ID. It returns a dictionary containing
    the user's details.
    Args:
        user_id (int): The unique identifier for the user.
    Returns:
        dict: A dictionary containing user data with keys like 'name',
              'email', and 'creation_date'.
    Raises:
        ConnectionError: If the database connection fails.
        ValueError: If the user_id is not a positive integer.
    """
    # ... function implementation ...
    pass

Breakdown of Sections

  • Summary Line (One Line):

    • A imperative, brief summary of the function's purpose.
    • Should not end with a period.
    • If the docstring is longer than one line, the summary is followed by a blank line.
    # Good
    def add(a, b):
        """Adds two numbers together."""
    # Bad
    def add(a, b):
        """This function adds two numbers together."""
  • Body (Optional):

    • A more detailed explanation of the function.
    • Can include usage examples, notes on implementation, etc.
    • Use the triple quotes to create a multi-line string.
  • Args (Arguments):

    • Describes the function's parameters.
    • Each argument is on its own line.
    • Format: name (type): description
    • If an argument has a complex type, you can be more specific (e.g., list[str]).
    def process_items(items: list[dict]) -> None:
        """Processes a list of items.
        Args:
            items (list[dict]): A list of dictionaries, where each dictionary
                represents an item with 'id' and 'value' keys.
        """
        # ...
  • Returns (Return Value):

    • Describes what the function returns.
    • Format: type: description
    • If the function returns None, you should state it.
    def is_even(number: int) -> bool:
        """Checks if a number is even.
        Args:
            number (int): The number to check.
        Returns:
            bool: True if the number is even, False otherwise.
        """
        # ...
  • Raises (Exceptions):

    • Documents the exceptions the function might raise.
    • Format: ExceptionType: description
    • This is extremely helpful for developers using your function.
    def divide(numerator: float, denominator: float) -> float:
        """Divides one number by another.
        Args:
            numerator (float): The number to be divided.
            denominator (float): The number to divide by.
        Returns:
            float: The result of the division.
        Raises:
            ZeroDivisionError: If the denominator is zero.
        """
        # ...
  • Examples (Optional but Highly Recommended):

    • Shows how to use the function.
    • Use the >>> prompt to indicate interactive Python sessions.
    def format_name(first_name: str, last_name: str) -> str:
        """Formats a person's full name.
        Args:
            first_name (str): The person's first name.
            last_name (str): The person's last name.
        Returns:
            str: The formatted full name, e.g., "Doe, John".
        Example:
            >>> format_name("John", "Doe")
            'Doe, John'
        """
        # ...

reStructuredText (reST) / Sphinx Style

This is the older, more formal standard. It uses directives (like param:) instead of section headers. It's the default for Sphinx, a tool for creating beautiful documentation websites from docstrings.

Basic Structure

"""[Summary line]
[Body paragraph]
:param [Argument Name]: [Description of the argument].
:type [Argument Name]: [Type of the argument]
:returns: [Description of the return value].
:rtype: [Type of the return value]
:raises [ErrorType]: [Description of the error].
"""
# Example:
def fetch_user_data(user_id: int) -> dict:
    """Fetches user data from the database.
    This function connects to the primary database and retrieves the profile
    information for the given user ID.
    :param user_id: The unique identifier for the user.
    :type user_id: int
    :returns: A dictionary containing user data.
    :rtype: dict
    :raises ConnectionError: If the database connection fails.
    :raises ValueError: If the user_id is not a positive integer.
    """
    # ... function implementation ...
    pass

NumPy/SciPy Style

This style is more verbose and is designed for complex, mathematical functions. It separates the type of each argument into its own section.

Basic Structure

"""[Summary line]
[Body paragraph]
Parameters
----------
[Argument Name] : [Type]
    [Description of the argument].
[Another Argument Name] : [Type]
    [Description of the argument].
Returns
-------
[Type]
    [Description of the return value].
Raises
------
[ErrorType]
    [Description of the error].
"""
# Example:
def calculate_distance(point_a: tuple, point_b: tuple) -> float:
    """Calculates the Euclidean distance between two points.
    This function computes the straight-line distance between two points
    in a 2D Cartesian plane.
    Parameters
    ----------
    point_a : tuple
        A tuple of (x, y) coordinates for the first point.
    point_b : tuple
        A tuple of (x, y) coordinates for the second point.
    Returns
    -------
    float
        The calculated Euclidean distance.
    Raises
    ------
    TypeError
        If the points are not tuples or do not have two elements.
    """
    # ...
    pass

Best Practices & Tooling

  1. Type Hints: Use Python's type hints (def func(a: int) -> str:). They are not a replacement for docstrings, but they work together. The docstring describes the what and why, while the type hint describes the what (the type).

  2. Keep it Concise: Don't write a novel. Be clear, concise, and focus on the information that the next developer (including you!) will need.

  3. Document the "Why": Explain the purpose and behavior of the code. The code itself says how it works, but the docstring should explain why it's doing it.

  4. Automate with Tools:

    • IDEs: PyCharm and VS Code have built-in generators that can create a docstring skeleton for you. Right-click on a function and select "Generate Docstring".
    • pydoc-markdown: A tool to generate Markdown documentation from your docstrings.
    • Sphinx: The gold standard for generating full-featured websites from your docstrings.
    • pdoc: A simple tool to generate API documentation from your docstrings.

Summary: Which One to Choose?

Style Best For Pros Cons
Google Most projects. New codebases, general-purpose libraries. Easy to read, very popular, great IDE support. Not as formal as reST for massive projects.
reST/Sphinx Large, complex projects, public APIs, libraries requiring a formal documentation website. Mature, powerful, industry standard for scientific computing. Syntax can be more verbose and less human-friendly.
NumPy/SciPy Scientific computing, data analysis, mathematical functions. Excellent for documenting complex mathematical functions and parameters. Can be overkill for simple functions.

Final Recommendation: For new projects, start with Google Style. It's the most practical and widely understood format today.

分享:
扫描分享到社交APP
上一篇
下一篇