在发现这个问题后,我采用了以下方法,它是有效的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-dash 分隔的项目列表)只是为了匹配 Sphinx 提供的自动格式化。
一旦您花费这样的努力使“关键字参数”部分看起来像默认的“参数”部分,那么从一开始就自己编写参数部分可能会更容易(如其他答案中所述),但作为概念验证,如果您已经使用 Sphinx,这是一种实现漂亮的补充 **kwargs
外观的方法之一。
**kwargs
。它缺乏清晰度,没有文档支持,失去了IDE的支持,而且容易混淆。 - Basil Musa使用Sphinx解析Google风格的文档字符串
免责声明:未经测试。
从这个Sphinx文档字符串示例的摘录中,*args
和 **kwargs
保持未展开状态:
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.
我建议采用以下方法来实现紧凑性:
"""
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
...
请注意,对于带有**key
参数的情况,Optional
不是必需的。
否则,您可以尝试在其他参数
下显式列出*args
,并在关键字参数
下列出**kwargs
(请参见文档字符串部分):
"""
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
...
*args
作为位置参数不能放在param2=None
之后。 - Lohengrin在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
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
>>> import subprocess
>>> import inspect
>>> import print inspect.getsource(subprocess)
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()
other_silly_variable
不是一个kwargs参数,而是一个完全正常的参数。 - bugmenot123**kwargs
而不指定类型 - 正如来自sphinx扩展napolean的numpydoc example和pandas文档协作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
及其描述放在其他参数
部分 - 即使matplotlib文档指南中的示例也建议这样做。
如果还有其他人在寻找有效的语法,这里有一个示例文档字符串。这只是我自己的做法,希望对你有用,但我不能声称它符合任何特定的标准。
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
我无法找到文档的实际链接,但这个可以使用(使用 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
keyword
。 - James McKinneyOther Parameters
来记录 **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}``.
"""
subprocess.call(*popenargs, **kwargs)
。文档中记述为 subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
,其中 *
之后的所有内容都是在 **kwargs
中识别的键(或至少是常用的键)。 - nos