forked from bslatkin/effectivepython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathitem_009.py
More file actions
executable file
·311 lines (234 loc) · 6.79 KB
/
item_009.py
File metadata and controls
executable file
·311 lines (234 loc) · 6.79 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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#!/usr/bin/env PYTHONHASHSEED=1234 python3
# Copyright 2014-2024 Brett Slatkin, Pearson Education Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
### Start book environment setup
import random
random.seed(1234)
import logging
from pprint import pprint
from sys import stdout as STDOUT
# Write all output to a temporary directory
import atexit
import gc
import io
import os
import tempfile
TEST_DIR = tempfile.TemporaryDirectory()
atexit.register(TEST_DIR.cleanup)
# Make sure Windows processes exit cleanly
OLD_CWD = os.getcwd()
atexit.register(lambda: os.chdir(OLD_CWD))
os.chdir(TEST_DIR.name)
def close_open_files():
everything = gc.get_objects()
for obj in everything:
if isinstance(obj, io.IOBase):
obj.close()
atexit.register(close_open_files)
### End book environment setup
print("Example 1")
def take_action(light):
if light == "red":
print("Stop")
elif light == "yellow":
print("Slow down")
elif light == "green":
print("Go!")
else:
raise RuntimeError
print("Example 2")
take_action("red")
take_action("yellow")
take_action("green")
print("Example 3")
def take_match_action(light):
match light:
case "red":
print("Stop")
case "yellow":
print("Slow down")
case "green":
print("Go!")
case _:
raise RuntimeError
take_match_action("red")
take_match_action("yellow")
take_match_action("green")
print("Example 4")
try:
# This will not compile
source = """# Added these constants
RED = "red"
YELLOW = "yellow"
GREEN = "green"
def take_constant_action(light):
match light:
case RED: # Changed
print("Stop")
case YELLOW: # Changed
print("Slow down")
case GREEN: # Changed
print("Go!")
case _:
raise RuntimeError"""
eval(source)
except:
logging.exception('Expected')
else:
assert False
print("Example 5")
RED = "red"
YELLOW = "yellow"
GREEN = "green"
def take_truncated_action(light):
match light:
case RED:
print("Stop")
print("Example 6")
take_truncated_action(GREEN)
print("Example 7")
def take_debug_action(light):
match light:
case RED:
print(f"{RED=}, {light=}")
take_debug_action(GREEN)
print("Example 8")
def take_unpacking_action(light):
try:
(RED,) = (light,)
except TypeError:
# Did not match
pass
else:
# Matched
print(f"{RED=}, {light=}")
take_unpacking_action(GREEN)
print("Example 9")
import enum # Added
class ColorEnum(enum.Enum): # Added
RED = "red"
YELLOW = "yellow"
GREEN = "green"
def take_enum_action(light):
match light:
case ColorEnum.RED: # Changed
print("Stop")
case ColorEnum.YELLOW: # Changed
print("Slow down")
case ColorEnum.GREEN: # Changed
print("Go!")
case _:
raise RuntimeError
take_enum_action(ColorEnum.RED)
take_enum_action(ColorEnum.YELLOW)
take_enum_action(ColorEnum.GREEN)
print("Example 10")
for index, value in enumerate("abc"):
print(f"index {index} is {value}")
print("Example 11")
my_tree = (10, (7, None, 9), (13, 11, None))
print("Example 12")
def contains(tree, value):
if not isinstance(tree, tuple):
return tree == value
pivot, left, right = tree
if value < pivot:
return contains(left, value)
elif value > pivot:
return contains(right, value)
else:
return value == pivot
print("Example 13")
assert contains(my_tree, 9)
assert not contains(my_tree, 14)
for i in range(0, 14):
print(i, contains(my_tree, i))
print("Example 14")
def contains_match(tree, value):
match tree:
case pivot, left, _ if value < pivot:
return contains_match(left, value)
case pivot, _, right if value > pivot:
return contains_match(right, value)
case (pivot, _, _) | pivot:
return pivot == value
assert contains_match(my_tree, 9)
assert not contains_match(my_tree, 14)
for i in range(0, 14):
print(i, contains_match(my_tree, i))
print("Example 15")
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
print("Example 16")
obj_tree = Node(
value=10,
left=Node(value=7, right=9),
right=Node(value=13, left=11),
)
print("Example 17")
def contains_class(tree, value):
if not isinstance(tree, Node):
return tree == value
elif value < tree.value:
return contains_class(tree.left, value)
elif value > tree.value:
return contains_class(tree.right, value)
else:
return tree.value == value
assert contains_class(obj_tree, 9)
assert not contains_class(obj_tree, 14)
for i in range(0, 14):
print(i, contains_class(obj_tree, i))
print("Example 18")
def contains_match_class(tree, value):
match tree:
case Node(value=pivot, left=left) if value < pivot:
return contains_match_class(left, value)
case Node(value=pivot, right=right) if value > pivot:
return contains_match_class(right, value)
case Node(value=pivot) | pivot:
return pivot == value
assert contains_match_class(obj_tree, 9)
assert not contains_match_class(obj_tree, 14)
for i in range(0, 14):
print(i, contains_match_class(obj_tree, i))
print("Example 19")
record1 = """{"customer": {"last": "Ross", "first": "Bob"}}"""
record2 = """{"customer": {"entity": "Steve's Painting Co."}}"""
print("Example 20")
from dataclasses import dataclass
@dataclass
class PersonCustomer:
first_name: str
last_name: str
@dataclass
class BusinessCustomer:
company_name: str
print("Example 21")
import json
def deserialize(data):
record = json.loads(data)
match record:
case {"customer": {"last": last_name, "first": first_name}}:
return PersonCustomer(first_name, last_name)
case {"customer": {"entity": company_name}}:
return BusinessCustomer(company_name)
case _:
raise ValueError("Unknown record type")
print("Example 22")
print("Record1:", deserialize(record1))
print("Record2:", deserialize(record2))