5

sphinx-doc napoleon Google style docstrings example here for version 1.3.4 显示函数/方法的可选参数应记录如下:

param2 (str, optional): The second parameter. Defaults to None.
  Second line of description should be indented.

但是这里1.4a0 版本的同一页面显示了以下方式来做同样的事情:

param2 (Optional[str]): The second parameter. Defaults to None.
    Second line of description should be indented.

但是我在文档中没有看到对这种新语法的任何解释。我在哪里可以找到有关 Google 样式文档字符串中支持的新语法的更多信息,其中包含 sphinx-doc 的拿破仑扩展?

4

2 回答 2

6

以 tl;dr 的方式:

查看您链接的函数module_level_function开头的文档,可以看到:

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 ``Args`` section. The name
    of each parameter is required. The type and description of each parameter
    is optional, but should be included if not obvious.

    Parameter types -- if given -- should be specified according to
    `PEP 484`_, though `PEP 484`_ conformance isn't required or enforced.

    # ^^^^^ this! ^^^^

最后一行包含一个提示。PEP 484显然,由模块辅助引入的符号typing就是您所看到的。


关于符号的小介绍:

PEP 484基于函数注释,如 中所述PEP 3107;本质上,每个函数参数的名称后都可以有一个可选的类型说明符。所以,对于像这样的功能:

def foo(a, b): 
    pass

您可以通过以下方式注释它们的类型:

def foo(a: int, b: str) -> None:
    pass

类型提示的引入带来了形式化类型指示方式的需要;这就是typing模块的用武之地。

typing模块包含一组很好的抽象类型(以及通常的类型理论 mumbo-jumbo),供您指定标准内置以外的其他类型,例如int, stret al. 例如,Optional[str]符号表示参数可以采用str类型或“类型”,None即它是可选的字符串。

所以简而言之,他们使用通过引入类型提示定义的符号来记录参数的类型。这意味着,如果您有一个函数,其参数是整数列表

 def func(param1)

它的文档应该是这样的:

param1 (List[int]): The first parameter containing a list of ints

List[int]来自打字模块中的符号的地方。


更多示例:

可以在(启发的静态检查器)的文档中mypy找到定义并进一步解释此特定符号的一些示例PEP 484。可能需要在其代码中记录的常见情况包含在内置类型表中

Type                Description
----                -----------

int                 integer of arbitrary size
float               floating point number
bool                boolean value
str                 unicode string
bytes               8-bit string
object              an arbitrary object (object is the common base class)
List[str]           list of str objects
Dict[str, int]      dictionary from str keys to int values
Iterable[int]       iterable object containing ints
Sequence[bool]      sequence of booleans
Any                 dynamically typed value with an arbitrary type

其他,likeAny, Union在这里定义,而通用符号在这里描述。

于 2016-01-20T12:32:22.800 回答
1

The Optional[X] syntax isn't specific to sphinx-doc, as far as I understand. It's from the typing module for type hints: https://docs.python.org/3/library/typing.html

于 2016-01-20T11:05:41.017 回答