如何为dict添加python docstring

web*_*org 12 python dictionary docstring

为字典参数添加docstring的推荐方法是什么?我可以在这里看到多行doc-string示例.

我需要在docstring中记录函数的输入参数.如果它是一个简单的变量,我可以使用类似的东西:

 def func2(a=x, b = y):
 """ fun2 takes two integers 

 Keyword arguments:
 a -- refers to age (default 18)
 b -- refers to experience (default 0)
 """
Run Code Online (Sandbox Code Playgroud)

如果我们dict作为输入参数传递给函数:

 def func3(**kwargs):
     """ takes dictionary as input

      <Here how to explain them - Is it like?> 
      kwargs['key1'] -- takes value1

      <or simply>
      key1 -- takes value1
      """
Run Code Online (Sandbox Code Playgroud)

jon*_*rpe 16

我通常使用Google docstring样式,因此字典参数如下所示:

def func(a_dict):
    """Some function to do something to a dictionary.

    Args:
      a_dict (dict of str: int): Some mapping, I guess?

    """
    ...
Run Code Online (Sandbox Code Playgroud)

采用的函数**kwargs(注意:这与具有字典参数完全相同),如下所示:

def func(**kwargs):
    """Some function to do stuff to arbitrary keyword arguments.

    Args:
      **kwargs: Arbitrary keyword arguments.

    """
    ...
Run Code Online (Sandbox Code Playgroud)

如果存在应该存在的特定参数(例如您的key1),则它们应该是分开的,而不是卷入的**kwargs.


在Python 3.x中,您还可以使用函数注释:

def func(a_dict: dict):
    """Some function to do something to a dictionary."""
    ...
Run Code Online (Sandbox Code Playgroud)

从Python 3.5开始,您可以更明确地使用typing:

from typing import Mapping

def func(a_dict: Mapping[str, int]):
    """Some function to do something to a dictionary."""
    ...
Run Code Online (Sandbox Code Playgroud)

  • 如果你想显式地输入字典的键和值怎么办?字典有 `class_ids` 有一个类型,`masks` 有一个类型......等等。 (2认同)
  • 您建议 Namgyal 的文档字符串“dict of str: int”很好。但我在您的 https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html 链接中没有看到任何描述 (2认同)