【笔记】Python3的TypeDict

前言

Python3通过TypeDict实现具有结构的字典

引入依赖

1
from typing import TypeDict

定义具有结构的字典

  • 默认在实例化时必须为所有属性赋值

  • 通过类语法定义

total:指定是否所有属性在实例化时都必须赋值

True:缺省值,所有属性在实例化时都必须赋值
False:所有属性在实例化时都不必须赋值

1
2
3
class 类名(TypeDict, total=True):
属性名1: str
属性名2: int
  • 通过TypeDict语法定义
1
2
3
4
5
6
7
8
类名 = TypeDict(
"类名",
{
属性名: str,
属性名: int
},
total = True
)

为指定属性设置为实例化时必须赋值

  • Python版本需>=3.11
1
2
3
4
5
from typing import Required

class 类名(TypeDict, total=False):
属性名1: Required[str]
属性名2: int

为指定属性设置为实例化时不必须赋值

  • Python版本需>=3.11
1
2
3
4
5
from typing import NotRequired

class 类名(TypeDict, total=True):
属性名1: NotRequired[str]
属性名2: int

为指定属性设置为只读属性

  • Python版本需>=3.13
1
2
3
4
5
6
from typing import ReadOnly
from typing import NotRequired

class 类名(TypeDict):
属性名1: ReadOnly[str]
属性名2: ReadOnly[NotRequired[int]]

实例化TypeDict对象

  • 通过定义字典的方式实例化TypeDict对象
1
变量名: 类名 = {"属性名1": "值", "属性名2": "值"}

将普通字典转换为TypeDict对象

1
2
3
4
from typing import cast

变量名 = dict()
cast(类名, 变量名)

完成

参考文献

哔哩哔哩——隔壁的程序员老王