我使用sphinx和autodoc插件为我的Python模块生成API文档。虽然我可以看到如何很好地记录特定参数,但我找不到如何记录**kwargs
参数的示例。什么是记录** kwargs参数的正确方法?
有没有人有一个清晰的方式来记录这些的很好的例子?
我使用sphinx和autodoc插件为我的Python模块生成API文档。虽然我可以看到如何很好地记录特定参数,但我找不到如何记录**kwargs
参数的示例。什么是记录** kwargs参数的正确方法?
有没有人有一个清晰的方式来记录这些的很好的例子?
我认为subprocess
-module's docs就是一个很好的例子。详细列出top/parent class的所有参数。然后,只需参考该列表中的所有其他出现**kwargs
。
我是唯一一个对这个答案没有意义的人吗?我找不到具体的例子。 – 2013-07-12 22:26:54
这个例子很可能是`subprocess.call(* popenargs,** kwargs)`。它被记录为`subprocess.call(args,*,stdin = None,stdout = None,stderr = None,shell = False)``*之后的所有内容都是`** kwargs`中的已识别键至少那些经常使用的) – nos 2014-01-11 00:39:08
如果其他人正在寻找一些有效的语法。这是一个示例docstring。这就是我如何做到的,我希望它对你有用,但我不能说它符合特别的任何事情。
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
斯芬克斯在他们的文档中有doctstring example。特别是它们显示出以下:
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
虽然你问sphinx明确,我也将指向Google Python Style Guide。他们的docstring例子似乎暗示他们没有专门叫出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快速查看模块文档。
使用无声幽灵的建议Python解释器的一个例子:
>>> import subprocess
>>> import inspect
>>> import print inspect.getsource(subprocess)
当然,你也可以查看通过帮助功能模块文档。例如,帮助(子进程)
我不是kwargs的子流程文档字符串的粉丝,但是像Google示例中那样,它并没有像Sphinx文档示例中所示的那样单独列出kwargs。
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()
我包括这个答案A-B-B的问题,因为这是值得注意的是,您可以查看任何模块的源代码或文档这样的洞察力和灵感注释你的代码。
发现这个问题,我在下面的解决,这是有效的狮身人面像和工作得相当好后:
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"""..."""
需要使这一“原始”文档字符串,从而保持\*
不变(为狮身人面像拾取作为一个字面*
而不是“重点”的开始)。
选择的格式(带圆括号的类型和m-dash分隔的说明的项目符号列表)仅用于匹配由Sphinx提供的自动格式。
一旦您将“关键字参数”部分看起来像默认的“参数”部分这样的努力,似乎可能更容易从一开始就推出自己的参数部分(根据一些其他答案),但作为概念验证,如果您已经在使用狮身人面像,这是一种实现漂亮外观**kwargs
的方法。
由狮身人面像
免责声明解析谷歌风格的文档字符串:未测试。
从这个缺口的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
和**kwargs
下的* ARGS的Keyword 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
...
这取决于您使用文档的风格,但如果你正在使用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的默认值,因为这些都不是从函数签名明显。
这完全取决于你使用什么docstring方法。 (reStructuredText,Sphinx,Google) – 2018-03-07 15:54:27