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

时间:2009-07-16 12:18:43

标签: python documentation python-sphinx

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

有没有人有一个明确的方法来记录这些?

8 个答案:

答案 0 :(得分:34)

在找到这个问题之后,我决定使用以下内容,这是有效的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"""..."""需要使其成为" raw" docstring因此保持\*完整(让Sphinx作为文字*而不是#34;强调")的开头。

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

一旦你完成了制作" Keyword Arguments"部分看起来像默认"参数"从一开始就可以更容易地推出自己的参数部分(根据其他一些答案),但作为概念证明,这是一种实现补充**kwargs的漂亮外观的方法如果您已经在使用Sphinx。

答案 1 :(得分:19)

Sphinx解析的Google Style文档字符串

免责声明:未经测试。

sphinx docstring example的这个剪影中,*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 
        ...

请注意,Optional参数不需要**key

否则,您可以尝试明确列出Other Parameters下的**kwargsKeyword Args下的* args(请参阅解析后的sections):

    """
    Args:
        param1 (int): The first parameter.
        param2 (Optional[str]): The second parameter. Defaults to None.
            Second line of description should be indented.

    Other Parameters:
        param3 (int): description
        param4 (str): 
        ...

    Keyword Args:
        key1 (int): description 
        key2 (int): description 
        ...

答案 2 :(得分:17)

我认为subprocess-module's docs就是一个很好的例子。列出top/parent class的所有参数的详尽列表。然后,只需参考该列表,查看**kwargs的所有其他事件。

答案 3 :(得分:7)

他们的文档中有一个doctstring example Sphinx。具体来说,他们显示以下内容:

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

虽然您明确询问了,但我也会指向Google Python Style Guide。他们的文档示例似乎暗示他们没有特别召唤出kwargs。 (other_silly_variable =无)

def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
"""Fetches rows from a Bigtable.

Retrieves rows pertaining to the given keys from the Table instance
represented by big_table.  Silly things may happen if
other_silly_variable is not None.

Args:
    big_table: An open Bigtable Table instance.
    keys: A sequence of strings representing the key of each table row
        to fetch.
    other_silly_variable: Another optional variable, that has a much
        longer name than the other args, and which does nothing.

Returns:
    A dict mapping keys to the corresponding table row data
    fetched. Each row is represented as a tuple of strings. For
    example:

    {'Serak': ('Rigel VII', 'Preparer'),
     'Zim': ('Irk', 'Invader'),
     'Lrrr': ('Omicron Persei 8', 'Emperor')}

    If a key from the keys argument is missing from the dictionary,
    then that row was not found in the table.

Raises:
    IOError: An error occurred accessing the bigtable.Table object.
"""
pass

A-B-B对引用子流程管理文档的接受答案有疑问。如果导入模块,则可以通过inspect.getsource快速查看模块文档字符串。

使用Silent Ghost推荐的python解释器的一个例子:

>>> import subprocess
>>> import inspect
>>> import print inspect.getsource(subprocess)

当然,您也可以通过帮助功能查看模块文档。例如help(subprocess)

我个人并不喜欢kwargs的子流程文档字符串的粉丝作为示例,但是像Google示例一样,它并没有单独列出kwargs,如Sphinx文档示例所示。

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()

我要回答AB-B的问题,因为值得注意的是,您可以通过这种方式查看任何模块的来源或文档,以获得有关评论的见解和灵感。代码。

答案 4 :(得分:5)

如果其他人正在寻找一些有效的语法..这是一个示例文档字符串。这就是我这样做的方式,我希望它对你有用,但我不能说它特别适合任何事情。

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

答案 5 :(得分:3)

如果您正在寻找如何以numpydoc样式进行操作,则只需在[Parameters]部分中提及**kwargs而无需指定类型-如{{3}中所示}来自狮身人面像扩展名Napolean,numpydoc example来自熊猫文档sprint 2018。

这是我从docstring guide找到的一个例子,很好地解释了**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及其描述放在Other Parameters部分-甚至来自LSST developer guide matplotlib文档指南建议相同。

答案 6 :(得分:2)

我无法找到文档的实际链接,但这有效(使用 Sphinx 3.4.3):

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

答案 7 :(得分:1)

这取决于您使用的文档样式,但如果您使用numpydoc样式,建议您使用Other Parameters记录**kwargs

例如,按照quornian的例子:

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的默认值,因为这些在函数签名中并不明显。