【问题标题】:Formatting python docstrings for dicts为dicts格式化python文档字符串
【发布时间】:2014-11-03 10:45:20
【问题描述】:

为字典参数添加文档字符串的推荐方法是什么?我可以看到多行文档字符串示例here

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

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

 Keyword arguments:
 a -- refers to age (default 18)
 b -- refers to experience (default 0)
 """

如果我们将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
      """

【问题讨论】:

  • 你能解释一下你的意思吗?你的意思是如何记录一个应该是字典的参数?
  • 是的,如何记录作为字典的参数。

标签: python dictionary docstring


【解决方案1】:

我一般使用Google docstring style,所以字典参数看起来像:

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

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

    """
    ...

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

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

    Args:
        **kwargs: Arbitrary keyword arguments.

    Keyword Args:
        <kwarg_name> int: A description
        <kwarg_name_2> str: Another description
        <...>

    """
    ...

如果应该存在特定参数(例如您的key1),它们应该是分开的,而不是滚动到**kwargs


在 Python 3.x 中,也可以使用function annotations

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

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

from typing import Mapping

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

【讨论】:

  • 如果你想明确地输入字典的键和值怎么办?字典有 class_ids 有一个类型,masks 有一个类型......等等。
  • @CMCDragonkai 我不知道有什么约定;如果这就是您想要的,那么您最好使用 namedtuple 之类的东西,并将其作为 attributes
  • 您建议 Namgyal 的文档字符串 dict of str: int 很好。但我在您指向sphinxcontrib-napoleon.readthedocs.io/en/latest/…的链接中没有看到任何描述
【解决方案2】:

对于使用 PyCharm 的用户:您可以在以下位置配置默认文档字符串格式:

Preferences -> Tools -> Python Integrated Tools -> Docstrings

从版本 2019 开始,允许的选项是:Plain、Epytext、reStructuredText、NumPy、Google。一旦您输入了三个双引号 " 并点击 enter,此功能将自动添加一个文档字符串框架。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 2021-01-17
    • 1970-01-01
    相关资源
    最近更新 更多