如何根据 Numpy 风格的文档字符串记录 kwargs?

Meh*_*edB 11 python numpy docstring python-3.x

因此,我找到了与其他样式相关的帖子,并且我知道有关文档的 NumPy 页面,但我很困惑我不明白如何将每个 kwargs 添加到方法的参数部分。这是来自给定的网页:

def foo(var1, var2, *args, long_var_name='hi', **kwargs):
    r"""Summarize the function in one line.

    Several sentences providing an extended description. Refer to
    variables using back-ticks, e.g. `var`.

    Parameters
    ----------
    var1 : array_like
        Array_like means all those objects -- lists, nested lists, etc. --
        that can be converted to an array.  We can also refer to
        variables like `var1`.
    var2 : int
        The type above can either refer to an actual Python type
        (e.g. ``int``), or describe the type of the variable in more
        detail, e.g. ``(N,) ndarray`` or ``array_like``.
    *args : iterable
        Other arguments.
    long_var_name : {'hi', 'ho'}, optional
        Choices in brackets, default first when optional.
    **kwargs : dict
        Keyword arguments.
Run Code Online (Sandbox Code Playgroud)

目前尚不清楚如何在此处添加每个 kwargs。我还看到了这个 sphinx 页面“Example NumPy Style Python Docstring”,这里是关于 kwargs 的部分:

def module_level_function(param1, param2=None, *args, **kwargs):
    """This is an example of a module level function.

    Function parameters should be documented in the ``Parameters`` section.
    The name of each parameter is required. The type and description of each
    parameter is optional, but should be included if not obvious.

    If \*args or \*\*kwargs are accepted,
    they should be listed as ``*args`` and ``**kwargs``.

    The format for a parameter is::

        name : type
            description

            The description may span multiple lines. Following lines
            should be indented to match the first line of the description.
            The ": type" is optional.

            Multiple paragraphs are supported in parameter
            descriptions.

    Parameters
    ----------
    param1 : int
        The first parameter.
    param2 : :obj:`str`, optional
        The second parameter.
    *args
        Variable length argument list.
    **kwargs
        Arbitrary keyword arguments. 
Run Code Online (Sandbox Code Playgroud)

不,我还是很困惑。是这样的吗?

"""
Dummy docstring.

Parameters
----------
**kwargs: dict
    first_kwarg: int
        This is an integer
    second_kwarg: str
        This is a string
"""
Run Code Online (Sandbox Code Playgroud)

np8*_*np8 9

概括

通常不会**kwargs在函数中列出,但**kwargs会提及其最终目的地。例如:

**kwargs
    Instructions on how to decorate your plots.
    The keyword arguments are passed to `matplotlib.axes.Axes.plot()` 
Run Code Online (Sandbox Code Playgroud)
  • 如果有多个可能的目标,则会全部列出(见下文)
  • 如果您碰巧使用某些自动化工具来插入和链接您的文档,那么您可能会列出可能的关键字参数,**kwargs以方便最终用户。例如,matplotlib 中就使用了这种方法。(见下文)

如何以及何时记录**kwargs(Numpydoc)

1)什么时候使用**kwargs

这里首先要注意的是**kwargs应该用于将参数传递给底层函数和方法。如果内部参数**kwargs将在函数中使用(并且不向下传递),则应将其写为普通关键字参数。

2)在哪里放置**kwargs描述?

描述的位置在该部分中。有时在该部分中列出它们是适当的,但请记住:仅当函数具有大量关键字参数时才应使用其他参数,以防止参数部分混乱。**kwargsParametersOther Parameters

  • matplotlib.axes.Axes.grid**kwargsParameters
  • matplotlib.axes.Axes.plot**kwargsinOther Parameters部分(可能对大量关键字参数进行推理)。

3)**kwargs描述语法

描述的语法是,**kwargs遵循Numpydoc 样式指南

Parameters
----------
... (other lines)
**kwargs : sometype
     Some description on what the kwargs are
     used for.
Run Code Online (Sandbox Code Playgroud)

或者

Parameters
----------
... (other lines)
**kwargs
     Some description on what the kwargs are
     used for.
Run Code Online (Sandbox Code Playgroud)

描述类型的更为合适,如 [ source ]。

对于参数类型,尽可能精确

一个例外是,例如,**kwargs 可以根据其他参数值将 传递给许多函数之一,如seaborn.kdeplot中。然后,类型的行将变得太长,无法描述所有类型,并且使用项目符号列表会更清晰,该列表还描述了何时将其**kwargs转发到何处的条件。例如。:

Parameters
----------
fill: bool or None
    If True, fill in the area under univariate density curves or between 
     bivariate contours. If None, the default depends on multiple.
**kwargs
    Other keyword arguments are passed to one of the following matplotlib 
    functions:

    * matplotlib.axes.Axes.plot() (univariate, fill=False),

    * matplotlib.axes.Axes.fill_between() (univariate, fill=True),

    * matplotlib.axes.Axes.contour() (bivariate, fill=False),

    * matplotlib.axes.contourf() (bivariate, fill=True).
Run Code Online (Sandbox Code Playgroud)

您还可以在like in 中添加有效关键字参数**kwargsmatplotlib.axes.Axes.grid的列表。这是插入的 python 文档/文本版本:

Parameters
----------
... (other lines)
**kwargs : `.Line2D` properties
    Define the line properties of the grid, e.g.::

        grid(color='r', linestyle='-', linewidth=2)

    Valid keyword arguments are:

    Properties:
    agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
    alpha: float or None
    animated: bool
    antialiased or aa: bool
    clip_box: `.Bbox`
    clip_on: bool
    clip_path: Patch or (Path, Transform) or None
    color or c: color
    contains: unknown
    dash_capstyle: {'butt', 'round', 'projecting'}
    dash_joinstyle: {'miter', '
    ... (more lines)
Run Code Online (Sandbox Code Playgroud)

这对于用户来说很方便,但对于开发人员来说却具有挑战性。在 matplotlib 中,这种奢侈是通过使用一些特殊的文档装饰器和链接1 的自动化来实现的。手动编写允许的 kwargs 肯定会成为代码维护的噩梦。

4) 相关注释**kwargs/扩展帮助

有关的一些附加信息**kwargs可以包含在该Notes部分中。例如,本节matplotlib.axes.Axes.plot讨论标记样式、线条样式和颜色Notes[2]


[1]他们使用一个@docstring.dedent_interpd装饰器将 kwargs 的含义拉到最终的文档中。例如,这就是代替 发生的%(Line2D:kwdoc)s
[2]请参阅:的实例在help(ax.plot)哪里。axmatplotlib.axes.Axes


A K*_*ger 6

通常,需要在本Parameters节中描述的 kwargs 通常会像其他命名参数一样进行处理,并且**kwargs不展开。然而,numpy 风格指南也有一个Other Parameters部分可用于提供 kwargs 的描述,而不会使该Parameters部分混乱。风格指南将其描述为:

用于描述不常用参数的可选部分。仅当函数具有大量关键字参数时才应使用它,以防止参数部分混乱。

numpydoc存储库给出了这个例子

"""

    Other Parameters
    ----------------
    only_seldom_used_keyword : int, optional
        Infrequently used parameters can be described under this optional
        section to prevent cluttering the Parameters section.
    **kwargs : dict
        Other infrequently used keyword arguments. Note that all keyword
        arguments appearing after the first parameter specified under the
        Other Parameters section, should also be described under this
        section.

"""
Run Code Online (Sandbox Code Playgroud)

因此,额外的 kwargs 可以添加为

"""

    Other Parameters
    ----------------
    first_kwarg: int
        This is an integer
    second_kwarg: str
        This is a string
    **kwargs : dict
        Other infrequently used keyword arguments.

"""
Run Code Online (Sandbox Code Playgroud)