Pep3107使用归档

Posted by xnchen on December 23, 2020

[TOC]

参考文档

python3 typing文档

简书:Python 函数注解与类型注解

基础知识

python的类型注解并不是强制的,而是用于静态检查(会在IDE之类的地方给出提示)。

基础形状

def test(
	input1: int,
  input2: np.ndarray = np.zeros(3, dtype=np.float32)
)-> tuple
	# ...

typing:类型标注支持

没有import typing的时候,python只能支持最基础的类型(int、float之类,list、tuple也没有办法深入到内部)。可以使用typing包对类型检查进行支持:

from typing import Dict, Tuple
def test(
	input1: int
) -> Tuple[np.ndarray, np.ndarry]

特殊的类型

typing.Union

使用Union[X, Y]来表示非X即Y的联合类型:

typing.Optional

Optional[X]等价于Union[X, None]

无法用静态检查的类

不能以静态方式推断的对象类型可以使用TypeVar表示

from typing import TypeVar
T = TypeVar("COCO", int, list)
def test()->T:
  # ...

IDE会静态地检测类型名字是不是在规定的参数范围内

Type.Any

所有类型均与Any兼容