← Back to index

typeddicts_readonly.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 5
FP: 0
FN: 1
Optional: 0 / 0
1"""
2Tests typing.ReadOnly qualifier introduced in PEP 705.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items
6
7from typing import Annotated, NotRequired, Required, TypedDict
8from typing_extensions import ReadOnly
9
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,
13# > or removed).
16class Band(TypedDict):
17 name: str
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}
50m1["title"] = "" # E
[invalid-assignment] Cannot assign to key "title" on TypedDict `Movie1`: key is marked read-only
51m1["year"] = 1992 # E
[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}
60m2["title"] = "" # E
[invalid-assignment] Cannot assign to key "title" on TypedDict `Movie2`: key is marked read-only
61m2["year"] = 1992 # E
[invalid-assignment] Cannot assign to key "year" on TypedDict `Movie2`: key is marked read-only