Python 记录**kwargs参数的正确方法是什么?

Python 记录**kwargs参数的正确方法是什么?,python,python-sphinx,autodoc,sphinx,Python,Python Sphinx,Autodoc,Sphinx,我正在使用和为Python模块生成API文档。虽然我知道如何很好地记录特定参数,但我找不到如何记录**kwargs参数的示例 有没有人有一个清晰的方法来记录这些内容的好例子?我认为这是一个好例子。给出一个完整的列表,其中列出了一个项目的所有参数。然后,如果其他人正在寻找一些有效的语法,只需参考该列表中所有其他出现的**kwargs。。下面是一个docstring示例。我就是这样做的,我希望它对你有用,但我不能说它符合任何特别的要求 def bar(x=True, y=False): ""

我正在使用和为Python模块生成API文档。虽然我知道如何很好地记录特定参数,但我找不到如何记录
**kwargs
参数的示例


有没有人有一个清晰的方法来记录这些内容的好例子?

我认为这是一个好例子。给出一个完整的列表,其中列出了一个项目的所有参数。然后,如果其他人正在寻找一些有效的语法,只需参考该列表中所有其他出现的
**kwargs

。。下面是一个docstring示例。我就是这样做的,我希望它对你有用,但我不能说它符合任何特别的要求

def bar(x=True, y=False):
    """
    Just some silly bar function.

    :Parameters:
      - `x` (`bool`) - dummy description for x
      - `y` (`string`) - dummy description for y
    :return: (`string`) concatenation of x and y.
    """
    return str(x) + y

def foo (a, b, **kwargs):
    """
    Do foo on a, b and some other objects.

    :Parameters:
      - `a` (`int`) - A number.
      - `b` (`int`, `string`) - Another number, or maybe a string.
      - `\**kwargs` - remaining keyword arguments are passed to `bar`

    :return: Success
    :rtype: `bool`
    """
    return len(str(a) + str(b) + bar(**kwargs)) > 20
在他们的文档中有一个关于斯芬克斯的描述。具体而言,它们显示了以下内容:

def public_fn_with_googley_docstring(name, state=None):
"""This function does something.

Args:
   name (str):  The name to use.

Kwargs:
   state (bool): Current state to be in.

Returns:
   int.  The return code::

      0 -- Success!
      1 -- No good.
      2 -- Try again.

Raises:
   AttributeError, KeyError

A really great idea.  A way you might use me is

>>> print public_fn_with_googley_docstring(name='foo', state=None)
0

BTW, this always returns 0.  **NEVER** use with :class:`MyPublicClass`.

"""
return 0
虽然你明确地问了这个问题,但我也要指出。他们的docstring示例似乎暗示他们并没有专门调用kwargs。(其他变量=无)

A-B-B对参考子流程管理文档的公认答案有疑问。如果导入模块,可以通过inspect.getsource快速查看模块docstring

使用Silent Ghost建议的python解释器示例:

>>> import subprocess
>>> import inspect
>>> import print inspect.getsource(subprocess)
当然,您也可以通过帮助功能查看模块文档。例如帮助(子流程)

我个人并不喜欢kwargs的子流程docstring作为示例,但与Google示例一样,它并没有像Sphinx文档示例中所示那样单独列出kwargs

def call(*popenargs, **kwargs):
"""Run command with arguments.  Wait for command to complete, then
return the returncode attribute.

The arguments are the same as for the Popen constructor.  Example:

retcode = call(["ls", "-l"])
"""
return Popen(*popenargs, **kwargs).wait()

我对A-B-B的问题给出了这个答案,因为值得注意的是,您可以通过这种方式查看任何模块的源代码或文档,以获得对代码进行评论的见解和灵感。

找到这个问题后,我解决了以下问题,这是有效的Sphinx,效果相当好:

def some_function(first, second="two", **kwargs):
    r"""Fetches and returns this thing

    :param first:
        The first parameter
    :type first: ``int``
    :param second:
        The second parameter
    :type second: ``str``
    :param \**kwargs:
        See below

    :Keyword Arguments:
        * *extra* (``list``) --
          Extra stuff
        * *supplement* (``dict``) --
          Additional content

    """
r”““…”
需要使其成为一个“原始”文档字符串,从而保持
\*
的完整性(Sphinx以文本形式拾取
*
,而不是“强调”的开头)

所选择的格式(带括号类型的项目符号列表和m-破折号分隔的描述)只是为了匹配Sphinx提供的自动格式


一旦你努力使“关键字参数”部分看起来像默认的“参数”部分,从一开始就滚动你自己的参数部分似乎更容易(根据其他一些答案),但是,作为概念证明,如果您已经在使用Sphinx,这是一种为补充的
**kwargs
提供漂亮外观的方法。

由Sphinx解析的谷歌风格的docstring

免责声明:未经测试

从的此切口中,
*args
**kwargs
未展开:

def module_level_function(param1, param2=None, *args, **kwargs):
    """
    ...

    Args:
        param1 (int): The first parameter.
        param2 (Optional[str]): The second parameter. Defaults to None.
            Second line of description should be indented.
        *args: Variable length argument list.
        **kwargs: Arbitrary keyword arguments.
我将建议以下紧凑性解决方案:

    """
    Args:
        param1 (int): The first parameter.
        param2 (Optional[str]): The second parameter. Defaults to None.
            Second line of description should be indented.
        *param3 (int): description
        *param4 (str): 
        ...
        **key1 (int): description 
        **key2 (int): description 
        ...
请注意,
**键
参数不需要
可选

否则,您可以尝试在
其他参数
下显式列出*args,并在
关键字args
下显式列出
**kwargs
(请参阅):


这取决于您使用的文档样式,但如果您使用的是这种样式,建议您使用
**kwargs
来编写文档

例如,以下是库尔尼安的例子:

def some_function(first, second="two", **kwargs):
    """Fetches and returns this thing

    Parameters
    ----------
    first : `int`
        The first parameter
    second : `str`, optional
        The second parameter

    Other Parameters
    ----------------
    extra : `list`, optional
        Extra stuff. Default ``[]``.
    suplement : `dict`, optional
        Additional content. Default ``{'key' : 42}``.
    """

特别要注意的是,建议给出kwargs的默认值,因为这些值在函数签名中并不明显。

如果您想了解如何在样式中实现这一点,您可以在参数部分简单地提及
**kwargs
,而无需指定类型
——如sphinx extension napolean和pandas文档sprint 2018中所示

下面是我发现的一个示例,它很好地解释了
**kwargs
参数的描述:

def demoFunction(namedArg, *args, flag=False, **kwargs):
    """Demonstrate documentation for additional keyword and
    positional arguments.

    Parameters
    ----------
    namedArg : `str`
        A named argument that is documented like always.
    *args : `str`
        Additional names.

        Notice how the type is singular since the user is expected to pass individual
        `str` arguments, even though the function itself sees ``args`` as an iterable
        of `str` objects).
    flag : `bool`
        A regular keyword argument.
    **kwargs
        Additional keyword arguments passed to `otherApi`.

        Usually kwargs are used to pass parameters to other functions and
        methods. If that is the case, be sure to mention (and link) the
        API or APIs that receive the keyword arguments.

        If kwargs are being used to generate a `dict`, use the description to
        document the use of the keys and the types of the values.
    """

或者,在@Jonas Adler建议的基础上,我发现最好将
**kwargs
及其描述放在
其他参数
部分
——甚至从matplotlib文档指南中也可以看出这一点。

我找不到文档的实际链接,但这是可行的(使用Sphinx 3.4.3):


我是唯一一个对此答案毫无意义的人吗?我找不到有问题的特定示例。该示例可能是
子流程.call(*popenargs,**kwargs)
。它被记录为
subprocess.call(args,*,stdin=None,stdout=None,stderr=None,shell=False)
,其中
*
后面的所有内容都是
**kwargs
中可识别的键(或至少是经常使用的键)最有意义的延续是现在,我不确定它是否是一个特别好的例子。除非我弄错了,否则它不再记录在中。否决投票因为没有在答案中包含一个实际的例子。那么单个关键字参数呢?我经常使用这个惯例,提及传递给哪个函数,但将定义留给拥有它们的func。当它们被重构时,多个docstring不需要更新。这完全取决于您使用的docstring方法。(StructuredText,Sphinx,Google)这本不应该关闭的。这是一个合理的问题。这是具体的(如何使用sphinx记录**kwargs),因为python中的文档注释不是完全标准化的。这将产生意见(或多种方法),只要它们专门支持问题(sphinx)。更正:这不是sphinx文档的一部分,而是独立的“示例pypi项目”的一部分,它明确地将自己描述为一个非权威的教程。
other_silly_variable
不是kwargs参数,而是一个完全正常的参数。我不确定您的建议是否来自旧文档或个人经验,但当前的“other Parameters”文档(您链接到的文档)声明它应该“用于
def some_function(first, second="two", **kwargs):
    """Fetches and returns this thing

    Parameters
    ----------
    first : `int`
        The first parameter
    second : `str`, optional
        The second parameter

    Other Parameters
    ----------------
    extra : `list`, optional
        Extra stuff. Default ``[]``.
    suplement : `dict`, optional
        Additional content. Default ``{'key' : 42}``.
    """
def demoFunction(namedArg, *args, flag=False, **kwargs):
    """Demonstrate documentation for additional keyword and
    positional arguments.

    Parameters
    ----------
    namedArg : `str`
        A named argument that is documented like always.
    *args : `str`
        Additional names.

        Notice how the type is singular since the user is expected to pass individual
        `str` arguments, even though the function itself sees ``args`` as an iterable
        of `str` objects).
    flag : `bool`
        A regular keyword argument.
    **kwargs
        Additional keyword arguments passed to `otherApi`.

        Usually kwargs are used to pass parameters to other functions and
        methods. If that is the case, be sure to mention (and link) the
        API or APIs that receive the keyword arguments.

        If kwargs are being used to generate a `dict`, use the description to
        document the use of the keys and the types of the values.
    """
class Foo:
    """A Foo implementation

    :param str foo: Foo
    :param int bar: Bar
    :keyword str key1: kwarg 1
    :keyword str key2: kwarg 2
    :keyword int key3: kwarg 3
    """

    def __init__(self, foo, bar, **kwargs):
        pass