from typing import TypedDict, ReadOnly class Leader(TypedDict): name: ReadOnly[str] age: int author: Leader = {'name': 'Yang Zhou', 'age': 30} author['age'] = 31 # no problem to change author['name'] = 'Yang'# Type check error: "name" is read-only
上面的代码展示了它的用法。由于我们将 name 属性定义为 ReadOnly[str]类型,因此更改其值将在集成开发环境或其他静态类型检查工具中调用类型不一致提示。
注意:“ReadOnly” 类型只能在 “TypedDict” 中使用。
如果你喜欢更简单的 TypedDict 定义方式,也可以使用 ReadOnly 类型:
from typing import TypedDict, ReadOnly Leader = TypedDict("Leader", {"name": ReadOnly[str], "age": int}) author: Leader = {'name': 'Yang Zhou', 'age': 30} author['age'] = 31# no problem to change author['name'] = 'Tim'# Type check error: "name" is read-only
from typing import TypeVar T = TypeVar("T", default=int) # This means that if no type is specified T is int print(T.has_default()) # True S = TypeVar("S") print(S.has_default()) # False
from typing import TypeVar, NoDefault T = TypeVar("T") print(T.__default__ is NoDefault) # True S = TypeVar("S", default=None) print(S.__default__ is NoDefault) # False