|
1 | 1 | """ |
2 | 2 | TODO: |
3 | 3 |
|
4 | | -Define a class `Point2D` that represents a dictionary with three string keys: |
5 | | - x, y, label |
| 4 | +Define a class `Student` that represents a dictionary with three keys: |
| 5 | +- name, a string |
| 6 | +- age, an integer |
| 7 | +- school, a string |
6 | 8 |
|
7 | | -The value of each key must be the specified type: |
8 | | - x - int, y - int, label - str |
9 | | -
|
10 | | -Note: label is optional |
| 9 | +Note: school can be optional |
11 | 10 | """ |
12 | 11 |
|
13 | 12 | from typing import TypedDict, NotRequired |
14 | 13 |
|
15 | 14 |
|
16 | | -class Point2D(TypedDict): |
17 | | - x: int |
18 | | - y: int |
19 | | - label: NotRequired[str] |
| 15 | +class Student(TypedDict): |
| 16 | + name: str |
| 17 | + age: int |
| 18 | + school: NotRequired[str] |
20 | 19 |
|
21 | 20 |
|
22 | 21 | # Alternatively you can write: |
23 | | -# Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': NotRequired[str]}) |
| 22 | +# Student = TypedDict('Student', {'name': str, 'age': int, 'school': str}) |
| 23 | + |
24 | 24 |
|
25 | 25 | ## End of your code ## |
26 | | -a: Point2D = {"x": 1, "y": 2} |
27 | | -a: Point2D = {"x": 1, "y": 2, "label": "good"} |
28 | | -a: Point2D = {"x": 1, "z": 2, "label": "good"} # expect-type-error |
29 | | -a: Point2D = {(1,): 1, "y": 2, "label": "good"} # expect-type-error |
30 | | -a: Point2D = {"x": 1, "y": "2", "label": "good"} # expect-type-error |
31 | | -b: Point2D = {"z": 3, "label": "bad"} # expect-type-error |
32 | | -assert Point2D(x=1, y=2) == dict(x=1, y=2) |
33 | | -assert Point2D(x=1, y=2, label="first") == dict(x=1, y=2, label="first") |
| 26 | +a: Student = {"name": "Tom", "age": 15} |
| 27 | +a: Student = {"name": "Tom", "age": 15, "school": "Hogwarts"} |
| 28 | +a: Student = {"name": 1, "age": 15, "school": "Hogwarts"} # expect-type-error |
| 29 | +a: Student = {(1,): "Tom", "age": 2, "school": "Hogwarts"} # expect-type-error |
| 30 | +a: Student = {"name": "Tom", "age": "2", "school": "Hogwarts"} # expect-type-error |
| 31 | +a: Student = {"z": "Tom", "age": 2} # expect-type-error |
| 32 | +assert Student(name="Tom", age=15) == dict(name="Tom", age=15) |
| 33 | +assert Student(name="Tom", age=15, school="Hogwarts") == dict( |
| 34 | + name="Tom", age=15, school="Hogwarts" |
| 35 | +) |
0 commit comments