Python核心库-TypeDict

5 阅读1分钟

TypeDict

给字典拍张证件照

1.先拍照(写类)

from typing import TypedDict

class Book(TypedDict):
    title: str
    price: float

2.拍照后,字典必须长这样

book: Book = {"title": "Python", "price": 39.8}   # ✔
bad: Book  = {"title": "Python"}                  # ✘ 缺 price,IDE 会提醒

3.运行时仍是普通dict,不额外占内存,也不自动检查,只是让IDE/静态工具帮你找错。

4.可选字段加 total=False 或 NotRequired(3.11+)

class Book(TypedDict, total=False):
    title: str
    price: float
  • total=False —— 整张模板默认“全可选”,再单独把个别字段标回“必需”。
  • NotRequired —— 每张模板默认“全必需”,再单独把个别字段标成“可选”。
  1. total=False(老写法,3.8 就有)
from typing import TypedDict, Required   # Required 3.11+,老版本用 typing-extensions

class User(TypedDict, total=False):
    id: Required[int]      # 在“全可选”里挑一个“必需”
    name: str              # 可选
    age: int               # 可选
  • 字典里 可以 没有 nameage
  • 必须id,否则 mypy/IDE 报错。
  1. NotRequired(新写法,Python 3.11 内置)
from typing import TypedDict, NotRequired   # 3.8~3.10 需 pip install typing-extensions

class User(TypedDict):
    id: int                # 默认“必需”
    name: NotRequired[str] # 单独把这一个变成可选
    age: NotRequired[int]  # 同上