jkp*_*jkp 80 python documentation python-sphinx
我正在使用sphinx和autodoc插件为我的Python模块生成API文档.虽然我可以看到如何很好地记录特定参数,但我找不到如何记录**kwargs参数的示例.
有没有人有一个明确的方法来记录这些?
quo*_*ian 38
在找到这个问题后,我决定使用以下内容,这是有效的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
"""
Run Code Online (Sandbox Code Playgroud)
的r"""..."""要求,使这个"原始"文档字符串,从而保持\*完好(为狮身人面像拿起作为文字*"强调",而不是开始).
选择的格式(带有括号类型和m-dash分隔描述的项目符号列表)只是为了匹配Sphinx提供的自动格式.
一旦你努力使"关键字参数"部分看起来像默认的"参数"部分,似乎从一开始就推出自己的参数部分可能更容易(根据其他一些答案) ,但作为概念证明,**kwargs如果您已经在使用Sphinx ,这是获得补充的好方法的一种方法.
Ole*_*leg 19
由Sphinx解析的Google Style文档字符串
免责声明:未经测试.
从这个缺口的的狮身人面像文档字符串例子中,*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.
Run Code Online (Sandbox Code Playgroud)
我建议以下解决紧凑性的方法:
"""
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
...
Run Code Online (Sandbox Code Playgroud)
请注意参数Optional不是必需的**key.
否则,你可以尝试明确列出下的*ARGS Other Parameters和**kwargs下Keyword Args(见解析的部分):
"""
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
...
Run Code Online (Sandbox Code Playgroud)
Sil*_*ost 15
我认为subprocess-module的文档就是一个很好的例子.列出顶级/父级的所有参数的详尽列表.然后只需参考该列表中的所有其他事件**kwargs.
在他们的文档中有Sphinx 的doctstring示例.具体来说,它们显示如下:
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
Run Code Online (Sandbox Code Playgroud)
虽然您明确询问了狮身人面像,但我也会指向Google Python样式指南.他们的文档示例似乎暗示他们没有具体说出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
Run Code Online (Sandbox Code Playgroud)
ABB对引用子流程管理文档的接受答案提出了疑问.如果导入模块,则可以通过inspect.getsource快速查看模块文档字符串.
使用Silent Ghost建议的python解释器的一个例子:
>>> import subprocess
>>> import inspect
>>> import print inspect.getsource(subprocess)
Run Code Online (Sandbox Code Playgroud)
当然,您也可以通过帮助功能查看模块文档.例如帮助(子进程)
作为一个例子,我不是个人喜欢kwargs的子进程文档字符串的粉丝,但是像Google示例一样,它没有单独列出kwargs,如Sphinx文档示例中所示.
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()
Run Code Online (Sandbox Code Playgroud)
我将此答案包含在ABB的问题中,因为值得注意的是,您可以通过这种方式查看任何模块的源代码或文档,以获得对代码进行评论的见解和灵感.
如果其他人正在寻找一些有效的语法.. 这是一个示例文档字符串。这就是我所做的,我希望它对您有用,但我不能声称它符合任何特定要求。
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
Run Code Online (Sandbox Code Playgroud)
如果您正在寻找如何以numpydoc样式执行此操作,您可以简单地在参数部分提及**kwargs而不指定类型- 如sphinx 扩展napolean中的numpydoc 示例和pandas 文档sprint 2018 中的docstring 指南所示。
下面是我从发现一个例子的LSST开发人员指南这很好解释了什么是应该是描述的**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.
"""
Run Code Online (Sandbox Code Playgroud)
或者,根据@Jonas Adler 的建议,我发现最好将**kwargs和它的描述放在Other Parameters部分中- 即使是 matplotlib 文档指南中的这个例子也表明了同样的意思。
这取决于您使用的文档风格,但如果您使用numpydoc风格,建议**kwargs使用Other Parameters.
例如,以下 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}``.
"""
Run Code Online (Sandbox Code Playgroud)
特别注意,建议给出 kwargs 的默认值,因为这些从函数签名中并不明显。
我无法找到文档的实际链接,但这有效(使用 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30974 次 |
| 最近记录: |