用法:
class typing.TypedDict(dict)向字典添加類型提示的特殊構造。在運行時,它是一個普通的
dict。TypedDict聲明了一個字典類型,它期望它的所有實例都有一組特定的鍵,其中每個鍵都與一個一致類型的值相關聯。這種期望不會在運行時檢查,但僅由類型檢查器強製執行。用法:class Point2D(TypedDict): x: int y: int label: str a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')允許在不支持的舊版本 Python 中使用此函數PEP 526,
TypedDict支持另外兩種等效的句法形式:Point2D = TypedDict('Point2D', x=int, y=int, label=str) Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})當任何鍵不是有效的標識符和關鍵字時,也應該使用函數語法,例如因為它們是關鍵字或包含連字符。例子:
# raises SyntaxError class Point2D(TypedDict): in: int # 'in' is a keyword x-y: int # name with hyphens # OK, functional syntax Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})默認情況下,所有鍵都必須存在於
TypedDict中。可以通過指定整體來覆蓋它。用法:class Point2D(TypedDict, total=False): x: int y: int這意味著
Point2DTypedDict可以省略任何鍵。類型檢查器僅應支持文字False或True作為total參數的值。True是默認值,它使類主體中定義的所有項都成為必需項。TypedDict類型可以使用基於類的語法從一個或多個其他TypedDict類型繼承。用法:class Point3D(Point2D): z: intPoint3D具有三個項目:x、y和z。它等價於這個定義:class Point3D(TypedDict): x: int y: int z: intTypedDict不能從非 TypedDict 類繼承,特別是包括Generic。例如:class X(TypedDict): x: int class Y(TypedDict): y: int class Z(object): pass # A non-TypedDict class class XY(X, Y): pass # OK class XZ(X, Z): pass # raises TypeError T = TypeVar('T') class XT(X, Generic[T]): pass # raises TypeErrorTypedDict可以通過注解字典(有關注解最佳實踐的更多信息,請參閱注解最佳實踐)、__total__、__required_keys__和__optional_keys__進行自省。參看PEP 589更多示例和詳細使用規則
TypedDict.3.8 版中的新函數。
相關用法
- Python typing.TypedDict.__optional_keys__用法及代碼示例
- Python typing.TypedDict.__total__用法及代碼示例
- Python typing.TypeVar用法及代碼示例
- Python typing.TypeGuard用法及代碼示例
- Python typing.Type用法及代碼示例
- Python typing.TypeAlias用法及代碼示例
- Python typing.TYPE_CHECKING用法及代碼示例
- Python typing.get_type_hints用法及代碼示例
- Python typing.Concatenate用法及代碼示例
- Python typing.Optional用法及代碼示例
- Python typing.Final用法及代碼示例
- Python typing.Protocol用法及代碼示例
- Python typing.NoReturn用法及代碼示例
- Python typing.is_typeddict用法及代碼示例
- Python typing.AsyncGenerator用法及代碼示例
- Python typing.final用法及代碼示例
- Python typing.ClassVar用法及代碼示例
- Python typing.ParamSpec用法及代碼示例
- Python typing.Literal用法及代碼示例
- Python typing.overload用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 typing.TypedDict。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
