1+ from typing import TypedDict , Tuple , Union
2+ from typing_extensions import NotRequired , Required
3+
4+
5+ # --- Class Based TypedDict ---
6+ class Movie (TypedDict , total = False ):
7+ title : Required [str ] # 5
8+ year : int
9+
10+
11+ m = Movie (title = 'The Matrix' , year = 1999 )
12+ # m = Movie()
13+ print (m )
14+
15+
16+ # --- Assignment Based TypedDict ---
17+ Movie2 = TypedDict ('Movie2' , {
18+ 'title' : Required [str ],
19+ 'year' : int ,
20+ }, total = False )
21+
22+
23+ m2 = Movie2 (title = 'The Matrix Reloaded' , year = 2003 )
24+ # m2 = Movie2()
25+ print (m2 )
26+
27+
28+ # --- Required[] outside of TypedDict (error) ---
29+ x : int = 5
30+ # x: Required[int] = 5
31+
32+
33+ # --- Required[] inside other Required[] (error) ---
34+ '''
35+ Movie3 = TypedDict('Movie3', {
36+ 'title': Required[Union[
37+ Required[str],
38+ bytes
39+ ]],
40+ 'year': int,
41+ }, total=False)
42+ '''
43+
44+
45+ # --- Required[] used within TypedDict but not at top level (error) ---
46+ '''
47+ Movie4 = TypedDict('Movie4', {
48+ 'title': Union[
49+ Required[str],
50+ bytes
51+ ],
52+ 'year': int,
53+ }, total=False)
54+ Movie5 = TypedDict('Movie5', {
55+ 'title': Tuple[
56+ Required[str],
57+ bytes
58+ ],
59+ 'year': int,
60+ }, total=False)
61+ '''
62+
63+
64+ # ==============================================================================
65+ # --- Class Based TypedDict ---
66+ class MovieN (TypedDict ):
67+ title : str
68+ year : NotRequired [int ]
69+
70+
71+ m = MovieN (title = 'The Matrix' , year = 1999 )
72+ # m = MovieN()
73+ print (m )
74+
75+
76+ # --- Assignment Based TypedDict ---
77+ MovieN2 = TypedDict ('MovieN2' , {
78+ 'title' : str ,
79+ 'year' : NotRequired [int ],
80+ })
81+
82+
83+ m2 = MovieN2 (title = 'The Matrix Reloaded' , year = 2003 )
84+ # m2 = MovieN2()
85+ print (m2 )
0 commit comments