|
11 | 11 |
|
12 | 12 | from typing import NotRequired, ReadOnly, TypedDict |
13 | 13 |
|
| 14 | +# %% Without ReadOnly |
| 15 | + |
14 | 16 | # class Version(TypedDict): |
15 | 17 | # version: str |
16 | 18 | # release_year: NotRequired[int | None] |
|
21 | 23 | # release_year: int |
22 | 24 |
|
23 | 25 |
|
| 26 | +# %% Using ReadOnly |
| 27 | +# |
| 28 | +# Can only use PythonVersion as a Version if the differing fields are ReadOnly |
24 | 29 | class Version(TypedDict): |
25 | | - version: ReadOnly[str] |
| 30 | + version: str |
26 | 31 | release_year: ReadOnly[NotRequired[int | None]] |
27 | 32 |
|
| 33 | + # Note that ReadOnly can be nested with other special forms in any order |
| 34 | + # release_year: NotRequired[ReadOnly[int | None]] |
| 35 | + |
28 | 36 |
|
29 | 37 | class PythonVersion(TypedDict): |
30 | | - version: ReadOnly[str] |
| 38 | + version: str |
31 | 39 | release_year: ReadOnly[int] |
32 | 40 |
|
33 | 41 |
|
34 | | -py313 = PythonVersion(version="3.13", release_year=2024) |
35 | | - |
36 | | -# Alternative syntax, using TypedDict as an annotation |
37 | | -# py313: PythonVersion = {"version": "3.13", "release_year": 2024} |
38 | | - |
39 | | - |
| 42 | +# %% Work with Version and PythonVersion |
| 43 | +# |
40 | 44 | def get_version_info(ver: Version) -> str: |
41 | 45 | if "release_year" in ver: |
42 | 46 | return f"Version {ver['version']} released in {ver['release_year']}" |
43 | 47 | else: |
44 | 48 | return f"Version {ver['version']}" |
45 | 49 |
|
46 | 50 |
|
47 | | -# Only allowed to use PythonVersion instead of Version if the fields are ReadOnly |
| 51 | +py313 = PythonVersion(version="3.13", release_year=2024) |
| 52 | + |
| 53 | +# Alternative syntax, using TypedDict as an annotation |
| 54 | +# py313: PythonVersion = {"version": "3.13", "release_year": 2024} |
| 55 | + |
48 | 56 | print(get_version_info(py313)) |
0 commit comments