← Back to index

typeddicts_required.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 1
FP: 0
FN: 3
Optional: 0 / 0
1"""
2Tests the Required and NotRequired special forms.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#required-and-notrequired
6
7from typing import Annotated, NotRequired, Required, TypedDict
8
9
10# Required and NotRequired are valid only within a TypedDict.
11class NotTypedDict:
12 x: Required[int] # E: Required not allowed in this context
Expected a ty diagnostic for this line
15def func1(
16 x: NotRequired[int], # E: NotRequired not allowed in this context
[invalid-type-form] `NotRequired` is not allowed in function parameter annotations
17) -> None:
18 pass
21class TD1(TypedDict, total=False):
22 a: int
25class TD2(TD1, total=True):
26 b: int
29class TD3(TypedDict):
30 a: NotRequired[int]
31 b: Required[int]
34class TD4(TypedDict, total=False):
35 a: int
36 b: Required[int]
39class TD5(TypedDict, total=True):
40 a: NotRequired[int]
41 b: int
44td3: TD3 = {"b": 0}
45td4: TD4 = {"b": 0}
46td5: TD5 = {"b": 0}
48# These are all equivalent types, so they should be
49# bidirectionally type compatible.
50td3 = td4
51td3 = td5
52td4 = td3
53td4 = td5
54td5 = td3
55td5 = td4
58class TD6(TypedDict):
59 a: Required[Required[int]] # E: Nesting not allowed
Expected a ty diagnostic for this line
60 b: Required[NotRequired[int]] # E: Nesting not allowed
Expected a ty diagnostic for this line
63class TD7(TypedDict):
64 # > Required[] and NotRequired[] can be used with Annotated[], in any nesting order.
65 x: Annotated[Required[int], ""]
66 y: Required[Annotated[int, ""]]
67 z: Annotated[Required[Annotated[int, ""]], ""]
70RecursiveMovie = TypedDict(
71 "RecursiveMovie", {"title": Required[str], "predecessor": NotRequired["RecursiveMovie"]}
72)
74movie: RecursiveMovie = {"title": "Beethoven 3", "predecessor": {"title": "Beethoven 2"}}