2Tests typing.ReadOnly qualifier introduced in PEP 705.
5# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items
7from typing import Annotated, NotRequired, Required, TypedDict
8from typing_extensions import ReadOnly
11# > The ``typing.ReadOnly`` type qualifier is used to indicate that an item
12# > declared in a ``TypedDict`` definition may not be mutated (added, modified,
18 members: ReadOnly[list[str]]
21b1: Band = {"name": "blur", "members": []}
23b1["name"] = "Blur" # OK
24b1["members"] = ["Damon Albarn"] # E
[invalid-assignment] Cannot assign to key "members" on TypedDict `Band`: key is marked read-only
25b1["members"].append("Damon Albarn") # OK
28# > The :pep:`alternative functional syntax <589#alternative-syntax>` for
29# > TypedDict also supports the new type qualifier.
31Band2 = TypedDict("Band2", {"name": str, "members": ReadOnly[list[str]]})
33b2: Band2 = {"name": "blur", "members": []}
35b2["name"] = "Blur" # OK
36b2["members"] = ["Damon Albarn"] # E
Expected a ty diagnostic for this line
37b2["members"].append("Damon Albarn") # OK
40# > ``ReadOnly[]`` can be used with ``Required[]``, ``NotRequired[]`` and
41# > ``Annotated[]``, in any nesting order.
44class Movie1(TypedDict):
45 title: ReadOnly[Required[str]] # OK
46 year: ReadOnly[NotRequired[Annotated[int, ""]]] # OK
49m1: Movie1 = {"title": "", "year": 1991}
[invalid-assignment] Cannot assign to key "title" on TypedDict `Movie1`: key is marked read-only
[invalid-assignment] Cannot assign to key "year" on TypedDict `Movie1`: key is marked read-only
54class Movie2(TypedDict):
55 title: Required[ReadOnly[str]] # OK
56 year: Annotated[NotRequired[ReadOnly[int]], ""] # OK
59m2: Movie2 = {"title": "", "year": 1991}
[invalid-assignment] Cannot assign to key "title" on TypedDict `Movie2`: key is marked read-only
[invalid-assignment] Cannot assign to key "year" on TypedDict `Movie2`: key is marked read-only