Python 3 Type hints cheat sheet
本文是关于如何给 Python 3 代码写类型注解的 cheat sheet。
- 赋值:
a: int = 1 - 声明:
a: int - 内建类型:
x: int,x: float,x: bool,x: str,x: bytes,x: List[int],x: Set[int],x: Dict[str, float],x: Tuple[int, str, float] - 可能为空:
x: Optional[str] - 函数:
def a(n: int) -> str: - 可能为两种类型:
x: Union[str, int] - 函数调用只能用位置,不能用名字传入参数:
def x(__y: int): x(1) 可以,x(__y=1) 会调用失败 - 类型 Any 表示什么都可以
- 值初始化为 [], 或 None 的时候,最好给出类型注解
- 忽略错误或警告:
# type: ignore, 通过写 comment cast(List[int], a)可以给 mypy 做类型转换,但它不是运行时的检查。- 鸭子类型:
Iterable[int],Mapping[int, str],MutableMapping[int, str] - 类变量:
ClassVar[int] - 正则:
Match[str] - 文件类似的对象:
IO[str] - 使用类的名字声明:
def f(foo: 'MyClass') -> int