-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathType-guided-refactorings.py
More file actions
55 lines (40 loc) · 1.83 KB
/
Type-guided-refactorings.py
File metadata and controls
55 lines (40 loc) · 1.83 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
#exercise
# Try changing the type annotation of Person.preferred_operating_system from str to List[str].
# Run mypy on the code.
# It tells us different places that our code is now wrong, because we’re passing values of the wrong type.
# We probably also want to rename our field - lists are plural. Rename the field to preferred_operating_systems.
# Run mypy again.
# Fix all of the places that mypy tells you need changing. Make sure the program works as you’d expect.
from dataclasses import dataclass
from typing import List
@dataclass(frozen=True)
class Person:
name: str
age: int
preferred_operating_systems: List[str]
@dataclass(frozen=True)
class Laptop:
id: int
manufacturer: str
model: str
screen_size_in_inches: float
operating_system: str
def find_possible_laptops(laptops: List[Laptop], person: Person) -> List[Laptop]:
possible_laptops: List[Laptop] = []
for laptop in laptops:
if laptop.operating_system in person.preferred_operating_systems:
possible_laptops.append(laptop)
return possible_laptops
people = [
Person(name="Imran", age=22, preferred_operating_systems=["Ubuntu", "Arch Linux"]),
Person(name="Eliza", age=34, preferred_operating_systems=["Arch Linux"]),
]
laptops = [
Laptop(id=1, manufacturer="Dell", model="XPS", screen_size_in_inches=13, operating_system="Arch Linux"),
Laptop(id=2, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system="Ubuntu"),
Laptop(id=3, manufacturer="Dell", model="XPS", screen_size_in_inches=15, operating_system="ubuntu"),
Laptop(id=4, manufacturer="Apple", model="macBook", screen_size_in_inches=13, operating_system="macOS"),
]
for person in people:
possible_laptops = find_possible_laptops(laptops, person)
print(f"Possible laptops for {person.name}: {possible_laptops}")