Skip to content

类型标注

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] 的形式来定义一个联合类型。细节如下:

  • 参数必须是类型,而且必须至少有一个参数。
  • 联合类型的联合类型会被展开打平,比如:
1
Union[Union[int, str], float] == Union[int, str, float]
  • 仅有一个参数的联合类型会坍缩成参数自身,比如:
1
Union[int] == int  # The constructor actually returns int
  • 多余的参数会被跳过,比如:
1
Union[int, str, int] == Union[int, str]
  • 在比较联合类型的时候,参数顺序会被忽略,比如:
1
Union[int, str] == Union[str, int]
  • 你不能继承或者实例化一个联合类型。
  • 你不能写成 Union[X][Y]

你可以使用 Optional[X] 作为 Union[X, None] 的缩写。

typing.Optional

1
2
def foo(arg: Optional[int] = None) -> None:
    ...