typing 对类型提示的支持

typing 对类型提示的支持#

只读 ReadOnly#

ReadOnly 用于将 TypedDict 的项标记为只读的特殊的类型标注构造。

例如:

from typing import TypedDict, ReadOnly
class Movie(TypedDict):
   title: ReadOnly[str]
   year: int

def mutate_movie(m: Movie) -> None:
   m["year"] = 1999  # allowed
   m["title"] = "The Matrix"  # 类型检查错误
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Cell In[1], line 1
----> 1 from typing import TypedDict, ReadOnly
      2 class Movie(TypedDict):
      3    title: ReadOnly[str]

ImportError: cannot import name 'ReadOnly' from 'typing' (/opt/hostedtoolcache/Python/3.12.7/x64/lib/python3.12/typing.py)