Skip to content

Commit f52f136

Browse files
committed
complete type refactoring exercise
1 parent 6bb9d87 commit f52f136

1 file changed

Lines changed: 80 additions & 0 deletions

File tree

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
from dataclasses import dataclass
2+
from typing import List
3+
4+
5+
@dataclass(frozen=True)
6+
class Person:
7+
name: str
8+
age: int
9+
preferred_operating_systems: List[str]
10+
11+
12+
@dataclass(frozen=True)
13+
class Laptop:
14+
id: int
15+
manufacturer: str
16+
model: str
17+
screen_size_in_inches: float
18+
operating_system: str
19+
20+
21+
def find_possible_laptops(laptops: List[Laptop], person: Person) -> List[Laptop]:
22+
possible_laptops = []
23+
for laptop in laptops:
24+
if laptop.operating_system in person.preferred_operating_systems:
25+
possible_laptops.append(laptop)
26+
return possible_laptops
27+
28+
29+
people = [
30+
Person(name="Imran", age=22, preferred_operating_systems=["Ubuntu"]),
31+
Person(name="Eliza", age=34, preferred_operating_systems=["Arch Linux"]),
32+
]
33+
34+
laptops = [
35+
Laptop(
36+
id=1,
37+
manufacturer="Dell",
38+
model="XPS",
39+
screen_size_in_inches=13,
40+
operating_system="Arch Linux",
41+
),
42+
Laptop(
43+
id=2,
44+
manufacturer="Dell",
45+
model="XPS",
46+
screen_size_in_inches=15,
47+
operating_system="Ubuntu",
48+
),
49+
Laptop(
50+
id=3,
51+
manufacturer="Dell",
52+
model="XPS",
53+
screen_size_in_inches=15,
54+
operating_system="ubuntu",
55+
),
56+
Laptop(
57+
id=4,
58+
manufacturer="Apple",
59+
model="macBook",
60+
screen_size_in_inches=13,
61+
operating_system="macOS",
62+
),
63+
]
64+
65+
for person in people:
66+
possible_laptops = find_possible_laptops(laptops, person)
67+
print(f"Possible laptops for {person.name}: {possible_laptops}")
68+
69+
# After running the code with mypy, I found two type errors.
70+
# Error 1:
71+
# On line 30, mypy says that `preferred_operating_systems` is given as a `str`,
72+
# but the Person class expects a `list[str]`.
73+
# To fix this, the operating system should be passed inside a list instead of
74+
# passing it as a single string.
75+
76+
# Error 2:
77+
# The same problem happens on line 31. A `str` is passed when mypy expects
78+
# a `list[str]`.
79+
# This can also be fixed by changing the single operating system string into
80+
# a list of strings.

0 commit comments

Comments
 (0)