以 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
, str
et 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
在这里定义,而通用符号在这里描述。