Repository navigation
Expand file tree
/
Copy pathch11_errors.py
More file actions
140 lines (103 loc) · 4.24 KB
/
Copy pathch11_errors.py
File metadata and controls
140 lines (103 loc) · 4.24 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
"""Solutions: errors and exceptions (chapter 11).
Worked answers for exercises/ch11_errors.py. Try each exercise yourself
before reading its solution; the struggle is where the learning happens.
This file reuses the test functions from the exercise file, so running it
checks these solutions exactly the way your own code is checked:
python exercises/solutions/ch11_errors.py
Every line should say [solved]. Your answer does not need to match these
line by line; if the tests pass, it is a valid solution.
"""
import runpy
from collections.abc import Callable
from collections.abc import Iterator
from pathlib import Path
# Run the exercise file as a module (its main() does not run) to reuse its
# report() helper and test_... functions.
EXERCISES = runpy.run_path(
str(Path(__file__).resolve().parent.parent / "ch11_errors.py")
)
report = EXERCISES["report"]
def safe_int(text: str, default: int = 0) -> int:
try:
return int(text)
except ValueError: # only "not a number"; a TypeError is a real bug
return default
def check_safe_int() -> None:
report("1. safe_int", EXERCISES["test_safe_int"], safe_int)
def parse_age(text: str) -> int:
try:
age = int(text)
except ValueError as exc:
# "from exc" records the original error as __cause__.
raise ValueError(f"age must be a whole number, got {text!r}") from exc
if not 0 <= age <= 150:
raise ValueError(f"age out of range: {age}")
return age
def check_parse_age() -> None:
report("2. parse_age", EXERCISES["test_parse_age"], parse_age)
class InsufficientFunds(Exception):
def __init__(self, balance: float, amount: float) -> None:
# The message goes to Exception.__init__, which is what str() shows.
super().__init__(
f"cannot withdraw {amount:.2f} from a balance of {balance:.2f}"
)
self.balance = balance
self.amount = amount
self.shortfall = amount - balance
def check_insufficient_funds() -> None:
report("3. InsufficientFunds", EXERCISES["test_insufficient_funds"],
InsufficientFunds)
def retry(func: Callable[[], str], attempts: int) -> str:
for attempt in range(1, attempts + 1):
try:
return func()
except ConnectionError:
if attempt == attempts:
raise # out of attempts: re-raise the error we just caught
raise AssertionError("unreachable: the loop returns or raises")
def check_retry() -> None:
report("4. retry", EXERCISES["test_retry"], retry)
def validate_order(order: dict[str, object]) -> None:
errors: list[Exception] = []
if not order.get("item"):
errors.append(ValueError("item is required"))
quantity = order.get("quantity")
if not isinstance(quantity, int):
errors.append(TypeError("quantity must be an int"))
elif quantity < 1:
errors.append(ValueError("quantity must be at least 1"))
if "@" not in str(order.get("email", "")):
errors.append(ValueError("email needs an @"))
if errors:
raise ExceptionGroup("invalid order", errors)
def check_validate_order() -> None:
report("5. validate_order", EXERCISES["test_validate_order"], validate_order)
def leaves(group: BaseExceptionGroup) -> Iterator[BaseException]:
"""Yield the plain exceptions in a group, depth first, left to right."""
for exc in group.exceptions:
if isinstance(exc, BaseExceptionGroup):
yield from leaves(exc)
else:
yield exc
def split_errors(group: ExceptionGroup) -> tuple[list[str], list[str]]:
values: list[str] = []
types: list[str] = []
try:
raise group
except* ValueError as matched: # `matched` keeps the nesting, so walk it
values = [str(exc) for exc in leaves(matched)]
except* TypeError as matched:
types = [str(exc) for exc in leaves(matched)]
# Anything not matched above (say a KeyError) was re-raised already.
return values, types
def check_split_errors() -> None:
report("6. split_errors", EXERCISES["test_split_errors"], split_errors)
def main() -> None:
check_safe_int()
check_parse_age()
check_insufficient_funds()
check_retry()
check_validate_order()
check_split_errors()
if __name__ == "__main__":
main()