Skip to content

Commit c151c3d

Browse files
committed
type-guided
1 parent 2518525 commit c151c3d

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

type-guided.py

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

0 commit comments

Comments
 (0)