typing

发布时间 2023-10-09 16:05:31作者: bitterteaer

https://www.cnblogs.com/poloyy/p/15170297.html

Optional

Optional[int] 等价于 Union[int, None]
意味着:既可以传指定的类型 int,也可以传 None

Literal

一种类型,可用于向类型检查器指示相应的变量或函数参数具有与提供的文字(或多个文字之一)等效的值。例如:

def validate_simple(data: Any) -> Literal[True]:  # always returns True
    ...

MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
    ...

open_helper('/some/path', 'r')  # Passes type check
open_helper('/other/path', 'typo')  # Error in type checker

Literal[...]不能被子类化。在运行时,允许将任意值作为类型参数Literal[...],但类型检查器可能会施加限制。看PEP 586有关文字类型的更多详细信息。