This repository has been archived by the owner on Nov 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 64
/
jsonpets.py
63 lines (53 loc) · 1.58 KB
/
jsonpets.py
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
56
57
58
59
60
61
62
63
# Cats and Dogs
import sys
import json
from dataclasses import dataclass
@dataclass
class Animal:
pass
@dataclass
class Pet(Animal):
name: str
@dataclass
class Dog(Pet):
breed: str
leash_color: str
@dataclass
class Cat(Pet):
pattern: str
favorite_toy: str
def get_pets(raw: object) -> list[Cat | Dog]:
match raw:
case [*raw_pets]: # List of pets
return [get_pet(raw_pet) for raw_pet in raw_pets]
case {**raw_pet}: # Maybe a single pet
return [get_pet(raw_pet)]
case _:
raise TypeError(f"Neither a pet nor a list of pets: {raw}")
def get_pet(raw_pet: object) -> Cat | Dog:
match raw_pet:
case {"type": "cat", "name": str(name), "pattern": str(pattern), "favorite_toy": str(toy)}:
return Cat(name, pattern, toy)
case {"type": "dog", "name": str(name), "breed": str(breed), "leash_color": str(leash)}:
return Dog(name, breed, leash)
case {"type": "cat" | "dog"}:
raise TypeError(f"Malformed pet: {raw_pet}")
case _:
raise TypeError(f"Not a pet: {raw_pet}")
def main() -> None:
raw = json.load(sys.stdin)
for pet in get_pets(raw):
print(pet)
if __name__ == "__main__":
main()
# Example input:
#
# [
# {"type": "dog", "name": "Sorry", "breed": "mutt", "leash_color": "black"},
# {"type": "cat", "name": "Catelyn", "pattern": "tuxedo", "favorite_toy": "laser pointer"}
# ]
#
# Output:
#
# Dog(name='Sorry', breed='mutt', leash_color='black')
# Cat(name='Catelyn', pattern='tuxedo', favorite_toy='laser pointer')