-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4_required_read.py
More file actions
65 lines (46 loc) · 2.45 KB
/
4_required_read.py
File metadata and controls
65 lines (46 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
If the total argument of the TypedDict definition is False, the item is non-required.
Else, the item is required.
-- If the Required qualifier is present, the item is required.
-- If the NotRequired qualifier is present, the item is non-required.
It is valid to use Required[] and NotRequired[] even for items where it is redundant,
to enable additional explicitness if desired. Note that the value of total only affects items defined in the current class body, not in any base classes. Thus, inheritance can be used to create a TypedDict that mixes required and non-required items without using Required[] or NotRequired[].
The following example demonstrates some of these rules:
"""
from typing import TypedDict, NotRequired, Required, ReadOnly, Annotated
class Movie(TypedDict):
name: str # required, not read-only
year: int # required, not read-only
director: NotRequired[str] # non-required, not read-only
rating: NotRequired[ReadOnly[float]] # non-required, read-only
invalid: Required[
NotRequired[int]
] # type checker error: both Required and NotRequired used
class PartialMovie(TypedDict, total=False):
name: str # non-required, not read-only
year: Required[int] # required, not read-only
score: ReadOnly[float] # non-required, read-only
partial: PartialMovie = {"name": "myname", "year": 1955, "score": 1.2}
partial["score"] = 1.34232 # I tried to change the read only; not accepted since it is read only
# ___________________________________________________________________________________
class MovieWithExtras(TypedDict, extra_items=ReadOnly[int | str]):
name: str
year: int
m1 = MovieWithExtras(name="Blade Runner", year=1982) # OK
m2 = MovieWithExtras(
name="The Godfather", year=1972, director="Francis Ford Coppola", rating=9
) # OK
m3 = MovieWithExtras(
name="Inception", year=2010, budget=160.0
) # Type check error: budget must be int or str
# ___________________________________________________________________________________
# here extra items must be boolean (True or False)
class Movie(TypedDict, extra_items=bool):
name: str
a: Movie = {"name": "Blade Runner", "novel_adaptation": True} # OK
b: Movie = {
"name": "Blade Runner",
"year": 1982, # extra item can be any name but it needs to be boolean
} # Not OK. 'int' is not assignable to 'bool'
#Type "dict[str, str | int]" is not assignable to declared type "Movie"
# "Literal[1982]" is not assignable to "bool"