What is the correct way to document a **kwargs parameter?
I'm using Sphinx and the autodoc extension to generate API documentation for my Python modules. Whilst I can see how to nicely document specific parameters, I cannot find an example of how to document a **kwargs
parameter.
Does anyone have a good example of a clear way to document these?
After finding this question I settled on the following, which is valid Sphinx and works fairly well:
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
"""
The r"""..."""
is required to make this a "raw" docstring and thus keep the \*
intact (for Sphinx to pick up as a literal *
and not the start of "emphasis").
The chosen formatting (bulleted list with parenthesized type and m-dash-separated description) is simply to match the automated formatting provided by Sphinx.
Once you've gone to this effort of making the "Keyword Arguments" section look like the default "Parameters" section, it seems like it might be easier to roll your own parameters section from the outset (as per some of the other answers), but as a proof of concept this is one way to achieve a nice look for supplementary **kwargs
if you're already using Sphinx.
Google Style docstrings parsed by Sphinx
Disclaimer: not tested.
From this cutout of the sphinx docstring example, the *args
and **kwargs
are left unexpanded:
def module_level_function(param1, *args, param2=None, **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.
I would suggest the following solution for compactness:
"""
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
...
Notice how, Optional
is not required for **key
arguments.
Otherwise, you can try to explicitly list the *args under Other Parameters
and **kwargs
under the Keyword Args
(see docstring 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
...