You need to enable JavaScript to run this app. Python Google风格docstring多接口*args编写及Sphinx兼容方法
优惠活动
大模型
产品
解决方案
定价
更多

Python Google风格docstring多接口*args编写及Sphinx兼容方法

适配Sphinx解析的Google风格多调用形式docstring实现

原docstring的写法在Sphinx配合napoleon扩展解析Google风格文档的场景下,会出现两个常见问题:一是Args节点下直接夹杂互斥的参数分支,会被解析器判定为逻辑混乱的参数说明;二是异常条目用破折号分隔,不符合规范格式,容易被当成普通文本处理。

可直接落地的规范写法

def log(self, *args):
    """Logs data in-memory to a list container, associated with a unix-path-like key.

    This method supports two mutually exclusive call patterns for single-value and bulk logging.

    Args:
        *args: Variable length argument list, must match one of the supported signatures below:

            **Two-argument call:**
                - vpath (str): Unix-path-like virtual key to associate the stored value with
                - value (Any): Arbitrary value to save to the in-memory log container

            **Single-argument call:**
                - vpath_value_map (Dict[str, Any]): Key-value mapping of virtual paths and corresponding values to batch store

    Raises:
        TypeError: Thrown when the input argument count does not match either of the two supported call patterns.
    """
    if not (0 < len(args) < 3):
        raise TypeError("Method has to be called with either one or two arguments.")

可选增强

如果需要Sphinx生成更精准的签名展示,可以搭配typing.overload做类型重载定义,和上述docstring组合时不会产生解析冲突:

from typing import overload, Any, Dict

class InMemoryLogStore:
    @overload
    def log(self, vpath: str, value: Any) -> None: ...

    @overload
    def log(self, vpath_value_map: Dict[str, Any]) -> None: ...

    def log(self, *args):
        # 原有函数实现逻辑

规范匹配要点

  • 整体结构完全遵循Google风格docstring要求,没有使用非标准自定义语法
  • 嵌套的参数分支说明可以被sphinx.ext.napoleon扩展正确识别,不会出现参数列示不全、逻辑错位的问题
  • 异常条目统一使用冒号分隔的标准格式,替代原写法里的破折号,符合解析器的识别规则

内容的提问来源于stack exchange,提问作者Armin Schaare

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.12.03 05:45:08