类型标注
https://docs.python.org/zh-cn/3.7/library/typing.html?highlight=typing#module-typing
typing.Union
联合类型; Union[X, Y]
意味着:要不是 X,要不是 Y。
使用形如 Union[int, str]
的形式来定义一个联合类型。细节如下:
- 参数必须是类型,而且必须至少有一个参数。
- 联合类型的联合类型会被展开打平,比如:
| Union[Union[int, str], float] == Union[int, str, float]
|
| Union[int] == int # The constructor actually returns int
|
| Union[int, str, int] == Union[int, str]
|
| Union[int, str] == Union[str, int]
|
- 你不能继承或者实例化一个联合类型。
- 你不能写成
Union[X][Y]
。
你可以使用 Optional[X]
作为 Union[X, None]
的缩写。
typing.Optional
| def foo(arg: Optional[int] = None) -> None:
...
|