Skip to content

Commit 527becb

Browse files
committed
Type guided refactorings task
1 parent 625be12 commit 527becb

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#exercise
2+
# Try changing the type annotation of Person.preferred_operating_system from str to List[str].
3+
4+
# Run mypy on the code.
5+
6+
# It tells us different places that our code is now wrong, because we’re passing values of the wrong type.
7+
8+
# We probably also want to rename our field - lists are plural. Rename the field to preferred_operating_systems.
9+
10+
# Run mypy again.
11+
12+
# Fix all of the places that mypy tells you need changing. Make sure the program works as you’d expect.
13+
14+
from dataclasses import dataclass
15+
from typing import List
16+
17+
@dataclass(frozen=True)
18+
class Person:
19+
name: str
20+
age: int
21+
preferred_operating_systems: List[str]
22+
23+
24+
@dataclass(frozen=True)
25+
class Laptop:
26+
id: int
27+
manufacturer: str
28+
model: str
29+
screen_size_in_inches: float
30+
operating_system: str
31+
32+
33+
def find_possible_laptops(laptops: List[Laptop], person: Person) -> List[Laptop]:
34+
possible_laptops: List[Laptop] = []
35+
for laptop in laptops:
36+
if laptop.operating_system in person.preferred_operating_systems:
37+
possible_laptops.append(laptop)
38+
return possible_laptops
39+
40+
41+
people = [
42+
Person(name="Imran", age=22, preferred_operating_systems=["Ubuntu", "Arch Linux"]),
43+
Person(name="Eliza", age=34, preferred_operating_systems=["Arch Linux"]),
44+
]
45+
46+
laptops = [
47+
Laptop(id=1, manufacturer="Dell", model="XPS", screen_size_in_inches=13, operating_system="Arch Linux"),
48+
Laptop(id=2, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system="Ubuntu"),
49+
Laptop(id=3, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system="ubuntu"),
50+
Laptop(id=4, manufacturer="Apple", model="macBook", screen_size_in_inches=13, operating_system="macOS"),
51+
]
52+
53+
for person in people:
54+
possible_laptops = find_possible_laptops(laptops, person)
55+
print(f"Possible laptops for {person.name}: {possible_laptops}")

0 commit comments

Comments
 (0)