用法:
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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
