docstring

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
Document a Python module or class using Google-style docstrings following project conventions. The argument can be a class name or a module path.
遵循项目约定,使用Google风格的文档字符串为Python模块或类编写文档。传入的参数可以是类名或模块路径。

Instructions

操作步骤

  1. Determine what to document based on the argument:
    If a module path is provided (e.g.
    src/pipecat/audio/vad/vad_analyzer.py
    ):
    • Use that file directly
    If a class name is provided (e.g.
    VADAnalyzer
    ):
    • Search for
      class ClassName
      in
      src/pipecat/
    • If multiple files contain that class name, list all matches with their file paths, ask the user which one they want to document, and wait for confirmation
  2. Once the file is identified, read the module to understand its structure:
    • Identify all classes, functions, and important type aliases
    • Understand the purpose of each component
  3. Apply documentation in this order:
    • Module docstring (at top, after imports)
    • Class docstrings
    • __init__
      methods (always document constructor parameters)
    • Public methods (not starting with
      _
      )
    • Dataclass/config classes with field descriptions
  4. Skip documentation for:
    • Private methods (starting with
      _
      )
    • Simple dunder methods (
      __str__
      ,
      __repr__
      ,
      __post_init__
      )
    • Very simple pass-through properties
    • Already documented code - If a class, method, or function already has a complete docstring that follows the project style, do not modify it. A docstring is complete if it has:
      • A one-line summary
      • Args section (if it has parameters)
      • Returns section (if it returns something meaningful)
    • Only add or improve documentation where it is missing or incomplete
  1. 根据传入的参数确定要文档化的对象:
    如果提供的是模块路径(例如
    src/pipecat/audio/vad/vad_analyzer.py
    ):
    • 直接使用该文件
    如果提供的是类名(例如
    VADAnalyzer
    ):
    • src/pipecat/
      目录下搜索
      class ClassName
      定义
    • 如果多个文件包含该类名,列出所有匹配项及其文件路径,询问用户想要为哪个文件编写文档,等待用户确认
  2. 确定目标文件后,读取模块以理解其结构:
    • 识别所有类、函数和重要的类型别名
    • 理解每个组件的用途
  3. 按照以下顺序编写文档:
    • 模块文档字符串(位于顶部,导入语句之后)
    • 类文档字符串
    • __init__
      方法(务必记录构造函数的参数)
    • 公共方法(以下划线
      _
      开头的除外)
    • 带字段描述的数据类/配置类
  4. 以下内容无需编写文档:
    • 私有方法(以下划线
      _
      开头的)
    • 简单的特殊方法(
      __str__
      __repr__
      __post_init__
    • 非常简单的透传属性
    • 已编写完整文档的代码 - 如果类、方法或函数已经有符合项目风格的完整文档字符串,请勿修改。完整的文档字符串应包含:
      • 一行摘要
      • 参数部分(如果有参数)
      • 返回值部分(如果返回有意义的内容)
    • 仅在文档缺失或不完整的地方补充或完善文档

Module Docstring Format

模块文档字符串格式

python
"""[One-line description of module purpose].

[Optional: Longer explanation of functionality, key classes, or use cases.]
"""
Example:
python
"""Neuphonic text-to-speech service implementations.

This module provides WebSocket and HTTP-based integrations with Neuphonic's
text-to-speech API for real-time audio synthesis.
"""
python
"""[模块用途的一行描述]。

[可选:对功能、核心类或使用场景的详细说明。]
"""
示例:
python
"""Neuphonic文本转语音服务实现。

本模块提供基于WebSocket和HTTP的Neuphonic文本转语音API集成,用于实时音频合成。
"""

Class Docstring Format

类文档字符串格式

python
class ClassName:
    """One-line summary describing what the class does.

    [Longer description explaining purpose, behavior, and key features.
    Use action-oriented language.]

    [Optional: Event handlers, usage notes, or important caveats.]
    """
Example:
python
class FrameProcessor(BaseObject):
    """Base class for all frame processors in the pipeline.

    Frame processors are the building blocks of Pipecat pipelines, they can be
    linked to form complex processing pipelines. They receive frames, process
    them, and pass them to the next or previous processor in the chain.

    Event handlers available:

    - on_before_process_frame: Called before a frame is processed
    - on_after_process_frame: Called after a frame is processed

    Example::

        @processor.event_handler("on_before_process_frame")
        async def on_before_process_frame(processor, frame):
            ...

        @processor.event_handler("on_after_process_frame")
        async def on_after_process_frame(processor, frame):
            ...
    """
Note: When listing event handlers, do NOT use backticks. Include an
Example::
section (with double colon for Sphinx) showing the decorator pattern and function signature for each event.
python
class ClassName:
    """描述类功能的一行摘要。

    [对用途、行为和核心特性的详细说明。使用面向动作的语言。]

    [可选:事件处理器、使用说明或重要注意事项。]
    """
示例:
python
class FrameProcessor(BaseObject):
    """管道中所有帧处理器的基类。

    帧处理器是Pipecat管道的构建块,它们可以链接起来形成复杂的处理管道。帧处理器接收帧、处理帧,并将其传递给链中的下一个或上一个处理器。

    可用的事件处理器:

    - on_before_process_frame:在处理帧之前调用
    - on_after_process_frame:在处理帧之后调用

    示例::

        @processor.event_handler("on_before_process_frame")
        async def on_before_process_frame(processor, frame):
            ...

        @processor.event_handler("on_after_process_frame")
        async def on_after_process_frame(processor, frame):
            ...
    """
注意:列出事件处理器时,请勿使用反引号。需包含
Example::
部分(使用双冒号以适配Sphinx),展示每个事件的装饰器模式和函数签名。

Constructor (
__init__
) Format

构造函数(
__init__
)格式

python
def __init__(self, *, param1: Type, param2: Type = default, **kwargs):
    """Initialize the [ClassName].

    Args:
        param1: Description of param1 and its purpose.
        param2: Description of param2. Defaults to [default].
        **kwargs: Additional arguments passed to parent class.
    """
Example:
python
def __init__(
    self,
    *,
    api_key: str,
    voice_id: Optional[str] = None,
    sample_rate: Optional[int] = 22050,
    **kwargs,
):
    """Initialize the Neuphonic TTS service.

    Args:
        api_key: Neuphonic API key for authentication.
        voice_id: ID of the voice to use for synthesis.
        sample_rate: Audio sample rate in Hz. Defaults to 22050.
        **kwargs: Additional arguments passed to parent InterruptibleTTSService.
    """
python
def __init__(self, *, param1: Type, param2: Type = default, **kwargs):
    """初始化[ClassName]。

    参数:
        param1: param1的描述及其用途。
        param2: param2的描述。默认为[default]。
        **kwargs: 传递给父类的额外参数。
    """
示例:
python
def __init__(
    self,
    *,
    api_key: str,
    voice_id: Optional[str] = None,
    sample_rate: Optional[int] = 22050,
    **kwargs,
):
    """初始化Neuphonic TTS服务。

    参数:
        api_key: 用于身份验证的Neuphonic API密钥。
        voice_id: 用于合成的语音ID。
        sample_rate: 音频采样率(单位:Hz)。默认为22050。
        **kwargs: 传递给父类InterruptibleTTSService的额外参数。
    """

Method Docstring Format

方法文档字符串格式

python
async def method_name(self, param1: Type) -> ReturnType:
    """One-line summary of what method does.

    [Longer description if behavior isn't obvious.]

    Args:
        param1: Description of param1.

    Returns:
        Description of return value.

    Raises:
        ExceptionType: When this exception is raised.
    """
Example:
python
async def put(self, item: Tuple[Frame, FrameDirection, FrameCallback]):
    """Put an item into the priority queue.

    System frames (`SystemFrame`) have higher priority than any other
    frames. If a non-frame item is provided it will have the highest priority.

    Args:
        item: The item to enqueue.
    """
python
async def method_name(self, param1: Type) -> ReturnType:
    """方法功能的一行摘要。

    [如果行为不明显,则添加详细说明。]

    参数:
        param1: param1的描述。

    返回:
        返回值的描述。

    异常:
        ExceptionType: 触发该异常的场景。
    """
示例:
python
async def put(self, item: Tuple[Frame, FrameDirection, FrameCallback]):
    """将项目放入优先级队列。

    系统帧(`SystemFrame`)的优先级高于其他所有帧。如果传入非帧项目,它将拥有最高优先级。

    参数:
        item: 要入队的项目。
    """

Dataclass/Config Format

数据类/配置类格式

python
@dataclass
class ConfigName:
    """One-line description of configuration.

    [Explanation of when/how to use this config.]

    Parameters:
        field1: Description of field1.
        field2: Description of field2. Defaults to [default].
    """

    field1: Type
    field2: Type = default_value
Example:
python
@dataclass
class FrameProcessorSetup:
    """Configuration parameters for frame processor initialization.

    Parameters:
        clock: The clock instance for timing operations.
        task_manager: The task manager for handling async operations.
        observer: Optional observer for monitoring frame processing events.
    """

    clock: BaseClock
    task_manager: BaseTaskManager
    observer: Optional[BaseObserver] = None
python
@dataclass
class ConfigName:
    """配置用途的一行描述。

    [对配置使用场景/方式的说明。]

    参数:
        field1: field1的描述。
        field2: field2的描述。默认为[default]。
    """

    field1: Type
    field2: Type = default_value
示例:
python
@dataclass
class FrameProcessorSetup:
    """帧处理器初始化的配置参数。

    参数:
        clock: 用于计时操作的时钟实例。
        task_manager: 用于处理异步操作的任务管理器。
        observer: 用于监控帧处理事件的可选观察者。
    """

    clock: BaseClock
    task_manager: BaseTaskManager
    observer: Optional[BaseObserver] = None

Enum Documentation Format

枚举类文档格式

python
class EnumName(Enum):
    """One-line description of the enum purpose.

    [Longer description of how the enum is used.]

    Parameters:
        VALUE1: Description of VALUE1.
        VALUE2: Description of VALUE2.
    """

    VALUE1 = 1
    VALUE2 = 2
python
class EnumName(Enum):
    """枚举用途的一行描述。

    [对枚举使用方式的详细说明。]

    参数:
        VALUE1: VALUE1的描述。
        VALUE2: VALUE2的描述。
    """

    VALUE1 = 1
    VALUE2 = 2

Writing Style Guidelines

写作风格指南

  • Concise and professional - No casual language or filler words
  • Action-oriented - Start with verbs: "Processes...", "Manages...", "Converts..."
  • Purpose before implementation - Explain WHY before HOW
  • Clear parameter descriptions - Include type hints, defaults, and purpose
  • No redundant type info - Type hints are in the signature, don't repeat in description
  • Use backticks for code references - Wrap class names, method names, event names, parameter names, and code snippets in backticks
Good: "Neuphonic API key for authentication." Bad: "str: The API key (string) that is used for authenticating with Neuphonic."
Good: "Triggers
on_speech_started
when the
VADAnalyzer
detects speech." Bad: "Triggers on_speech_started when the VADAnalyzer detects speech."
  • 简洁专业 - 避免随意语言或冗余词汇
  • 面向动作 - 以动词开头:“处理...”、“管理...”、“转换...”
  • 先讲用途再讲实现 - 先解释“为什么”再说明“怎么做”
  • 清晰的参数描述 - 包含类型提示、默认值和用途
  • 无冗余类型信息 - 类型提示已在签名中,请勿在描述中重复
  • 代码引用使用反引号 - 将类名、方法名、事件名、参数名和代码片段用反引号包裹
正确示例:“用于身份验证的Neuphonic API密钥。” 错误示例:“str: 用于Neuphonic身份验证的API密钥(字符串)。”
正确示例:“当
VADAnalyzer
检测到语音时触发
on_speech_started
事件。” 错误示例:“当VADAnalyzer检测到语音时触发on_speech_started事件。”

Deprecation Notice Format

弃用通知格式

When documenting deprecated code:
python
"""[Description].

.. deprecated:: X.X.X
    `ClassName` is deprecated and will be removed in a future version.
    Use `NewClassName` instead.
"""
为已弃用的代码编写文档时:
python
"""[描述]。

.. deprecated:: X.X.X
    `ClassName` 已弃用,将在未来版本中移除。
    请改用 `NewClassName`。
"""

Checklist

检查清单

Before finishing, verify:
  • Module has a docstring at the top (after copyright header and imports)
  • All public classes have docstrings
  • All
    __init__
    methods document their parameters
  • All public methods have docstrings with Args/Returns/Raises as needed
  • Dataclasses use "Parameters:" section for field descriptions
  • Enums document each value in "Parameters:" section
  • Writing is concise and action-oriented
  • No documentation added to private methods (starting with
    _
    )
  • Existing complete docstrings were left unchanged
完成前,请验证:
  • 模块顶部(版权声明和导入语句之后)有文档字符串
  • 所有公共类都有文档字符串
  • 所有
    __init__
    方法都记录了参数
  • 所有公共方法都有文档字符串,并根据需要包含参数/返回值/异常部分
  • 数据类使用“Parameters:”部分描述字段
  • 枚举类在“Parameters:”部分记录每个值
  • 写作简洁且面向动作
  • 未为私有方法(以下划线
    _
    开头)添加文档
  • 已有的完整文档字符串未被修改