在哪里可以找到有关使用sphinx-doc的拿破仑扩展的Google风格文档字符串支持的新语法的更多信息?

Lon*_*ner 5 python python-sphinx

这里针对1.3.4版本的sphinx-doc拿破仑Google风格文档字符串示例显示函数/方法的可选参数应记录如下:

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

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

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

但是我没有在文档中看到对这种新语法的任何解释.在哪里可以找到有关使用sphinx-doc的拿破仑扩展的Google风格文档字符串支持的新语法的更多信息?

Jim*_*ard 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! ^^^^
Run Code Online (Sandbox Code Playgroud)

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


一个小的介绍符号:

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

def foo(a, b): 
    pass
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式注释其类型:

def foo(a: int, b: str) -> None:
    pass
Run Code Online (Sandbox Code Playgroud)

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

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

简而言之,他们使用通过引入类型提示定义的符号来记录参数的类型.这意味着如果你有一个函数接受一个整数列表的参数:

 def func(param1)
Run Code Online (Sandbox Code Playgroud)

它的文档应如下所示:

param1 (List[int]): The first parameter containing a list of ints
Run Code Online (Sandbox Code Playgroud)

哪里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
Run Code Online (Sandbox Code Playgroud)

其他的,像Any, Union在这里被定义而通用符号描述这里.


Wee*_*ble 1

Optional[X]据我了解,该语法并非特定于 sphinx-doc。它来自typing类型提示模块:https://docs.python.org/3/library/typing.html