记录在文档字符串中作为参数传递的字典

Ros*_*s W 10 python dictionary python-sphinx

相关内容:为 dicts 格式化 python 文档字符串

为作为参数传递给函数的字典提供文档的正确方法是什么?这是我编写的样式示例(基于 Sphinx 的 Google 文档样式):

def class_function_w_dict_argument(self, T_in, c_temps):
    """ This calculates things with temperatures

    Notes:
        All temperatures should be given in Kelvin

    Args:
        T_in (float): Known temperature (K)
        c_temps (dict): Dictionary of component temperatures
            {T1 (float): temperature (K)
             T2 (float): temperature (K)
             T3 (float): temperature (K)
             T4 (float): temperature (K)
             T5 (float): temperature (K)}

    Returns:
        T_out (float): Calculated temperature
    """
Run Code Online (Sandbox Code Playgroud)

pyg*_*eek 5

前言

\n

据我所知,没有 PEP 用于区分文档字符串中特定类型的输入参数。但是,Python 支持键入,这为 xe2x80x94 提供了进一步的上下文,并对 xe2x80x94 输入参数提供了显式约束。

\n

打字

\n

为此,我建议使用打字而不是使用文档字符串,因为字典数据形状很容易偏离正在记录的内容\xe2\x80\x94,唯一比没有文档更糟糕的是不正确的文档。

\n

此外,必须为每个将其作为输入参数的函数记录该字典是很麻烦的\xe2\x80\x94创建和维护可以在整个代码库中共享的类型更易于维护(和可测试)。

\n

例子

\n
from typing import TypedDict, NewType\n\nTemperature = NewType("Temperature", float)\n\nclass ComponentTemperatures(TypedDict):\n    T1: Temperature\n    T2: Temperature\n    T3: Temperature\n    T4: Temperature\n    T5: Temperature\n\ndef class_function_w_dict_argument(T_in, c_temps: ComponentTemperatures):\n  print(c_temps)\n\n\nc_temps = ComponentTemperatures({\n    "T1": Temperature(1.0),\n    "T2": Temperature(1.1),\n    "T3": Temperature(1.2),\n    "T4": Temperature(1.3),\n    "T5": Temperature(1.4),\n})\n\nclass_function_w_dict_argument(0, c_temps)\n
Run Code Online (Sandbox Code Playgroud)\n

要强制输入,请使用以下命令进行检查mypy

\n
$ mypy main.py \nSuccess: no issues found in 1 source file\n
Run Code Online (Sandbox Code Playgroud)\n

这是我用这个工作示例创建的 repl.it:https://replit.com/@pygeek1/python-typing

\n

笔记

\n
    \n
  1. 对于此数据,列表而不是字典可能是更合适的类型。

    \n
  2. \n
  3. mypy类型检查可以包含在您的 linter 和/或测试套件中。

    \n
  4. \n
  5. 该解决方案有许多变体,可以根据您的需要进行应用,例如允许任意数量的 Dict 项目,或者类型检查 dict 键而不是对其进行硬编码。

    \n
  6. \n
\n

参考

\n

https://docs.python.org/3/library/typing.html

\n

https://peps.python.org/pep-0589/

\n

http://mypy-lang.org

\n

/sf/answers/1869987171/

\n