You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PyCharm的reST/Sphinx格式文档字符串中为函数的字典参数标注可接受的键

解决方案:在reST/Sphinx Docstring中清晰展示配置字典的键

当然可以!在PyCharm默认的reST/Sphinx文档字符串格式下,你可以用缩进的带说明无序列表来明确列出配置字典的可接受键,PyCharm的函数悬停提示会正确解析并清晰展示这些内容。

以下是完整的示例代码,展示了如何规范编写docstring:

from typing import Any, List

# 假设你已经定义了这些类型
class Entry:
    pass

class ProcessedEntry:
    pass

class DataProcessingError(Exception):
    pass

def process_data(data: List[Entry], dict_with_config: dict[str, Any]) -> List[ProcessedEntry]:
    """
    Processes input data based on the provided configuration rules.

    :param data: Raw data entries waiting to be processed.
    :param dict_with_config: Configuration dictionary that accepts these keys:
        - `filter_empty`: bool (default: False)
          When set to True, removes any empty or null entries from the input data.
        - `output_format`: str (default: "standard")
          Determines the structure of processed output; valid options are "standard", "compact" or "verbose".
        - `batch_size`: int (default: 50)
          Controls the number of entries processed in one batch to balance speed and memory usage.
    :returns: List of fully processed data entries aligned with the configuration.
    :raises DataProcessingError: Thrown if invalid config values are passed or data is unprocessable.
    """
    # 函数逻辑实现
    pass

为什么这样有效?

  • PyCharm完全支持reST的缩进列表语法,悬停时会把每个键的说明以层级化的方式展示,可读性极强。
  • 用反引号(`)包裹键名,会让键在提示框中以代码样式高亮,和说明文字区分开。
  • 你还可以补充每个键的类型和默认值,让调用者更清楚参数要求。

如果想要更正式的结构化展示,也可以使用reST的定义列表格式,效果类似:

:param dict_with_config: Configuration dictionary that accepts these keys:
    `filter_empty`
        bool (default: False) — Filters out empty entries when enabled.
    `output_format`
        str (default: "standard") — Sets the output structure style.

不过无序列表的方式在PyCharm的提示框中看起来更紧凑清晰。

内容的提问来源于stack exchange,提问作者Vaclav Pelc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 06:27:45