简体   繁体   English

如何根据 Numpy 样式文档字符串记录 kwargs?

[英]How to document kwargs according to Numpy style docstring?

So, I've found posts related to other styles and I am aware of this NumPy page about the documentation but I am confused.所以,我找到了与其他 styles 相关的帖子,我知道这个NumPy 页面关于文档,但我很困惑。 I didn't understand how to add each kwargs to the parameters section of a method.我不明白如何将每个 kwargs 添加到方法的参数部分。 This is from the given web page:这是来自给定的 web 页面:

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.

It is not clear how to add each kwargs here.目前尚不清楚如何在此处添加每个 kwargs。 I also saw this sphinx page "Example NumPy Style Python Docstring" , here is the section about the 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. 

Nope, I am still confused.不,我仍然很困惑。 Is it something like this?是这样的吗?

"""
Dummy docstring.

Parameters
----------
**kwargs: dict
    first_kwarg: int
        This is an integer
    second_kwarg: str
        This is a string
"""

Summary概括

The **kwargs are not typically listed in the function, but instead the final destination of the **kwargs is mentioned. **kwargs通常不会在 function 中列出,而是会提到**kwargs的最终目的地。 For example:例如:

**kwargs
    Instructions on how to decorate your plots.
    The keyword arguments are passed to `matplotlib.axes.Axes.plot()` 
  • If there are multiple possible targets, they are all listed (see below)如果有多个可能的目标,则将它们全部列出(见下文)
  • If you happen to use some automation tool to interpolate and link your documentation, then you might list the possible keyword arguments in **kwargs for the convenience of the end users.如果你碰巧使用一些自动化工具来插入和链接你的文档,那么你可能会在**kwargs中列出可能的关键字 arguments 以方便最终用户。 This kind of approach is used in matplotlib, for example.例如,matplotlib 中使用了这种方法。 (see below) (见下文)

How and when document **kwargs (Numpydoc)如何以及何时记录**kwargs (Numpydoc)

1) When to use **kwargs ? 1)什么时候使用**kwargs

First thing to note here is that **kwargs should be used to pass arguments to underlying functions and methods .这里首先要注意的是,应该使用**kwargs将 arguments 传递给底层函数和方法 If the argument inside **kwargs would be used in the function (and not passed down), it should be written out as normal keyword argument, instead.如果**kwargs中的参数将在 function 中使用(而不是向下传递),则应将其写为普通关键字参数。

2) Where to put **kwargs decription? 2) **kwargs描述放在哪里?

The location of **kwargs description is in the Parameters section. **kwargs描述的位置Parameters部分。 Sometimes it is appropriate to list them in the Other Parameters section, but remember: Other Parameters should only be used if a function has a large number of keyword parameters, to prevent cluttering the Parameters section.有时将它们列在“ Other Parameters ”部分是合适的,但请记住:只有在 function 具有大量关键字参数时才应使用“其他参数”,以防止使“参数”部分混乱。

  • matplotlib.axes.Axes.grid has **kwargs in Parameters section. matplotlib.axes.Axes.gridParameters部分有**kwargs
  • matplotlib.axes.Axes.plot has **kwargs in Other Parameters section (reasoning probably to large number of keyword arguments). matplotlib.axes.Axes.plotOther Parameters部分有**kwargs (推理可能是大量关键字参数)。

3) Syntax for **kwargs decription 3) **kwargs描述的语法

The syntax for the description for the **kwargs is, following Numpydoc styleguide **kwargs描述的语法是,遵循Numpydoc styleguide

Parameters
----------
... (other lines)
**kwargs : sometype
     Some description on what the kwargs are
     used for.

or或者

Parameters
----------
... (other lines)
**kwargs
     Some description on what the kwargs are
     used for.

The one describing the type is more appropriate, as [ source ].描述类型的那个更合适,如 [ source ]。

For the parameter types, be as precise as possible对于参数类型,尽可能精确

One exception for this is for example when the **kwargs could be passed to one of many functions based on other parameter values , as in seaborn.kdeplot .例如,当**kwargs可以根据其他参数值传递给许多函数之一时,例如seaborn.kdeplot 就是一个例外。 Then, the line for the type would become too long for describing all the types and it would be cleaner to use a bullet point list, which also describes the conditions on when the **kwargs are forwarded to where.然后,类型的行会变得太长而无法描述所有类型,使用项目符号列表会更清晰,它还描述了何时将**kwargs转发到何处的条件。 Eg.:例如。:

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

You may also add listing of the valid keyword arguments in **kwargs like in matplotlib.axes.Axes.grid .您还可以**kwargs中添加有效关键字 arguments 的列表,例如matplotlib.axes.Axes.grid Here is the interpolated python doc/text version:这是内插的 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)

This is convenient for the user, but challenging for the developer.这对用户来说很方便,但对开发人员来说具有挑战性。 In matplotlib this kind of luxury is made possible with the automatization using some special documentation decorators and linking 1 .在 matplotlib 中,这种奢侈是通过使用一些特殊的文档装饰器和链接1的自动化实现的。 Manual writing of allowed kwargs will surely become a code maintenance nightmare.手动编写允许的 kwargs 肯定会成为代码维护的噩梦。

4) Notes related to **kwargs / Extended help 4) **kwargs相关的注释/扩展帮助

Some additional info about the **kwargs could be included in the Notes section.关于**kwargs的一些附加信息可以包含在Notes部分中。 For example matplotlib.axes.Axes.plot discusses marker styles, line styles and colors in the Notes section.例如matplotlib.axes.Axes.plotNotes部分讨论了标记 styles、行 styles 和 colors。 [2] [2]


[1] They use a @docstring.dedent_interpd decorator which pulls the meaning of the kwargs to the final docs. [1]他们使用@docstring.dedent_interpd装饰器将 kwargs 的含义提取到最终文档中。 So that is happening in place of %(Line2D:kwdoc)s , for example.例如,这代替了%(Line2D:kwdoc)s
[2] See: help(ax.plot) where ax is instance of matplotlib.axes.Axes . [2]请参阅: help(ax.plot) ,其中axmatplotlib.axes.Axes的实例。

Usually kwargs that need to be described in the Parameters section would typically be handled like other named arguments and the **kwargs is left unexpanded.通常需要在Parameters部分描述的 kwargs 通常会像其他命名的 arguments 一样处理,并且**kwargs保持未扩展。 However, the numpy style guide also has an Other Parameters section than can be used for providing descriptions of kwargs without cluttering the Parameters section.但是,numpy 样式指南也有一个Other Parameters部分,可用于提供 kwargs 的描述,而不会使Parameters部分混乱。 The style guide describes it as: 风格指南将其描述为:

An optional section used to describe infrequently used parameters.用于描述不经常使用的参数的可选部分。 It should only be used if a function has a large number of keyword parameters, to prevent cluttering the Parameters section.仅当 function 具有大量关键字参数时才应使用它,以防止参数部分混乱。

The numpydoc repo gives this example : numpydoc repo 给出了这个例子

"""

    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.

"""

So, the additional kwargs could be added as因此,额外的 kwargs 可以添加为

"""

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

"""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM