docstring

docstring

熱門

遵循 PyTorch 規範為 PyTorch 的函式與方法撰寫 docstring。適用於在 PyTorch 程式碼中撰寫或更新 docstring 的情境。

10萬星標
2.9萬分支
更新於 2026/8/2
SKILL.md
唯讀
名稱
docstring
描述

遵循 PyTorch 規範為 PyTorch 的函式與方法撰寫 docstring。適用於在 PyTorch 程式碼中撰寫或更新 docstring 的情境。

PyTorch Docstring 撰寫指南

本 Skill 說明如何遵循 torch/_tensor_docs.pytorch/nn/functional.py 中的慣例,為 PyTorch 專案中的函式與方法撰寫 docstring。

一般原則

  • 所有 docstring 皆使用原始字串r"""..."""),避免 LaTeX/數學公式的反斜線衍生問題
  • 說明文件遵循 Sphinx/reStructuredText (reST) 格式
  • 精簡但完整——包含所有關鍵資訊
  • 只要情況允許,務必附上範例
  • 使用交叉參照(cross-references)連結至相關的函式/類別

Docstring 結構

1. 函式簽章(第一行)

開頭請提供顯示所有參數的函式簽章:

r"""function_name(param1, param2, *, kwarg1=default1, kwarg2=default2) -> ReturnType

注意事項:

  • 需包含函式名稱
  • 標示位置引數與僅限關鍵字引數(使用 * 分隔符)
  • 包含預設值
  • 標示回傳型別標註
  • 此行結尾切勿加上句點

2. 簡短說明

提供一行說明,概要描述函式的功能:

r"""conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) -> Tensor

Applies a 2D convolution over an input image composed of several input
planes.

3. 數學公式(若適用)

數學運算式請使用 Sphinx 的 math 指令:

.. math::
    \text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}

或是行內數學公式::math:\x^2``

4. 交叉參照

使用 Sphinx role 連結至相關的類別與函式:

  • :class:\~torch.nn.ModuleName`` - 連結至類別
  • :func:\torch.function_name`` - 連結至函式
  • :meth:\~Tensor.method_name`` - 連結至方法
  • :attr:\attribute_name`` - 參照屬性
  • 使用 ~ 前綴可以只顯示最後一個元件名稱(例如顯示 Conv2d 而非 torch.nn.Conv2d

範例:

See :class:`~torch.nn.Conv2d` for details and output shape.

5. 注意事項與警告

使用提示框(admonition)標示重要資訊:

.. note::
    This function doesn't work directly with NLLLoss,
    which expects the Log to be computed between the Softmax and itself.
    Use log_softmax instead (it's faster and has better numerical properties).

.. warning::
    :func:`new_tensor` always copies :attr:`data`. If you have a Tensor
    ``data`` and want to avoid a copy, use :func:`torch.Tensor.requires_grad_`
    or :func:`torch.Tensor.detach`.

6. Args 區段

說明所有參數並包含型別標註與詳細描述:

Args:
    input (Tensor): input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
    weight (Tensor): filters of shape :math:`(\text{out\_channels} , kH , kW)`
    bias (Tensor, optional): optional bias tensor of shape :math:`(\text{out\_channels})`. Default: ``None``
    stride (int or tuple): the stride of the convolving kernel. Can be a single number or a
      tuple `(sH, sW)`. Default: 1

排版規則:

  • 參數名稱使用小寫
  • 型別放在括號中:選用參數寫為 (Type)(Type, optional)
  • 描述接在型別之後
  • 對於選用參數,請在末尾加上 "Default: value"
  • 行內程式碼請使用雙反引號:``None``
  • 換行接續的行請縮排 2 個空格

7. Keyword Args 區段(若適用)

關鍵字引數有時會單獨列出說明:

Keyword args:
    dtype (:class:`torch.dtype`, optional): the desired type of returned tensor.
        Default: if None, same :class:`torch.dtype` as this tensor.
    device (:class:`torch.device`, optional): the desired device of returned tensor.
        Default: if None, same :class:`torch.device` as this tensor.
    requires_grad (bool, optional): If autograd should record operations on the
        returned tensor. Default: ``False``.

8. Returns 區段(若需要)

說明回傳值:

Returns:
    Tensor: Sampled tensor of same shape as `logits` from the Gumbel-Softmax distribution.
        If ``hard=True``, the returned samples will be one-hot, otherwise they will
        be probability distributions that sum to 1 across `dim`.

若從上下文已足夠明確,亦可直接標示於函式簽章行中。

9. Examples 區段

只要情況允許,務必附上範例:

Examples::

    >>> inputs = torch.randn(33, 16, 30)
    >>> filters = torch.randn(20, 16, 5)
    >>> F.conv1d(inputs, filters)

    >>> # With square kernels and equal stride
    >>> filters = torch.randn(8, 4, 3, 3)
    >>> inputs = torch.randn(1, 4, 5, 5)
    >>> F.conv2d(inputs, filters, padding=1)

排版規則:

  • 使用帶有雙冒號的 Examples::
  • Python 程式碼使用 >>> 提示符號
  • 有助於理解時請加上 # 註解
  • 在有助於理解的情況下呈現實際輸出(不加 >>> 並進行縮排)

10. 外部參考資料

連結至論文或外部文件:

.. _Link Name:
    https://arxiv.org/abs/1611.00712

在正文中引用:See `Link Name`_

方法類型

原生 Python 函式

一般的 Python 函式,請使用標準的 docstring:

def relu(input: Tensor, inplace: bool = False) -> Tensor:
    r"""relu(input, inplace=False) -> Tensor

    Applies the rectified linear unit function element-wise. See
    :class:`~torch.nn.ReLU` for more details.
    """
    # implementation

C 語言綁定函式(使用 add_docstr)

對於 C 語言綁定的函式,請使用 _add_docstr

conv1d = _add_docstr(
    torch.conv1d,
    r"""
conv1d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) -> Tensor

Applies a 1D convolution over an input signal composed of several input
planes.

See :class:`~torch.nn.Conv1d` for details and output shape.

Args:
    input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iW)`
    weight: filters of shape :math:`(\text{out\_channels} , kW)`
    ...
""",
)

原地操作變體(In-Place Variants)

對於原地操作(名稱以 _ 結尾),請直接參照原始函式:

add_docstr_all(
    "abs_",
    r"""
abs_() -> Tensor

In-place version of :meth:`~Tensor.abs`
""",
)

別名函式(Alias Functions)

對於別名函式,只需直接參照原始函式:

add_docstr_all(
    "absolute",
    r"""
absolute() -> Tensor

Alias for :func:`abs`
""",
)

常見模式

形狀說明(Shape Documentation)

Tensor 形狀請使用 LaTeX 數學標記法:

:math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`

可重複使用的引數定義

針對常用的引數,可先定義一次後重複使用:

common_args = parse_kwargs(
    """
    dtype (:class:`torch.dtype`, optional): the desired type of returned tensor.
        Default: if None, same as this tensor.
"""
)

# Then use with .format():
r"""
...

Keyword args:
    {dtype}
    {device}
""".format(**common_args)

樣板插入(Template Insertion)

插入可重複性說明(reproducibility notes)或其他通用文字:

r"""
{tf32_note}

{cudnn_reproducibility_note}
""".format(**reproducibility_notes, **tf32_notes)

完整範例

以下是包含所有要素的完整範例:

def gumbel_softmax(
    logits: Tensor,
    tau: float = 1,
    hard: bool = False,
    eps: float = 1e-10,
    dim: int = -1,
) -> Tensor:
    r"""
    Sample from the Gumbel-Softmax distribution and optionally discretize.

    Args:
        logits (Tensor): `[..., num_features]` unnormalized log probabilities
        tau (float): non-negative scalar temperature
        hard (bool): if ``True``, the returned samples will be discretized as one-hot vectors,
              but will be differentiated as if it is the soft sample in autograd. Default: ``False``
        dim (int): A dimension along which softmax will be computed. Default: -1

    Returns:
        Tensor: Sampled tensor of same shape as `logits` from the Gumbel-Softmax distribution.
            If ``hard=True``, the returned samples will be one-hot, otherwise they will
            be probability distributions that sum to 1 across `dim`.

    .. note::
        This function is here for legacy reasons, may be removed from nn.Functional in the future.

    Examples::
        >>> logits = torch.randn(20, 32)
        >>> # Sample soft categorical using reparametrization trick:
        >>> F.gumbel_softmax(logits, tau=1, hard=False)
        >>> # Sample hard categorical using "Straight-through" trick:
        >>> F.gumbel_softmax(logits, tau=1, hard=True)

    .. _Link 1:
        https://arxiv.org/abs/1611.00712
    """
    # implementation

快速檢查清單

撰寫 PyTorch docstring 時,請確認:

  • [ ] 使用原始字串(r"""
  • [ ] 第一行為函式簽章
  • [ ] 提供簡短說明
  • [ ] 在 Args 區段詳細說明所有參數及其型別
  • [ ] 為選用參數加上預設值
  • [ ] 使用 Sphinx 交叉參照(:func:, :class:, :meth:
  • [ ] 若適用請加入數學公式
  • [ ] 在 Examples 區段至少附上一個範例
  • [ ] 針對重要注意事項加入警告或提示
  • [ ] 使用 :class: 連結至相關模組類別
  • [ ] Tensor 形狀使用正確的數學標記法
  • [ ] 遵循一致的格式與縮排

常見 Sphinx Role 參考

  • :class:\~torch.nn.Module`` - 類別參照
  • :func:\torch.function`` - 函式參照
  • :meth:\~Tensor.method`` - 方法參照
  • :attr:\attribute`` - 屬性參照
  • :math:\equation`` - 行內數學公式
  • :ref:\label`` - 內部參照
  • ``code`` - 行內程式碼(使用雙反引號)

額外注意事項

  • 縮排:程式碼使用 4 個空格,參數描述換行接續使用 2 個空格
  • 每行長度:儘可能將每行維持在 100 個字元以內
  • 句點:句子結尾請加句點,但簽章行末切勿加上句點
  • 反引號:程式碼請使用雙反引號:``True`` ``None`` ``False``
  • 型別:常見型別包含 Tensorintfloatboolstrtuplelist