forked from bslatkin/effectivepython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathitem_076.py
More file actions
executable file
·498 lines (388 loc) · 12.9 KB
/
item_076.py
File metadata and controls
executable file
·498 lines (388 loc) · 12.9 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
#!/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")
class EOFError(Exception):
pass
class Connection:
def __init__(self, connection):
self.connection = connection
self.file = connection.makefile("rb")
def send(self, command):
line = command + "\n"
data = line.encode()
self.connection.send(data)
def receive(self):
line = self.file.readline()
if not line:
raise EOFError("Connection closed")
return line[:-1].decode()
print("Example 2")
import random
WARMER = "Warmer"
COLDER = "Colder"
SAME = "Same"
UNSURE = "Unsure"
CORRECT = "Correct"
class UnknownCommandError(Exception):
pass
class ServerSession(Connection):
def __init__(self, *args):
super().__init__(*args)
self.clear_state()
print("Example 3")
def loop(self):
while command := self.receive():
match command.split(" "):
case "PARAMS", lower, upper:
self.set_params(lower, upper)
case ["NUMBER"]:
self.send_number()
case "REPORT", decision:
self.receive_report(decision)
case ["CLEAR"]:
self.clear_state()
case _:
raise UnknownCommandError(command)
print("Example 4")
def set_params(self, lower, upper):
self.clear_state()
self.lower = int(lower)
self.upper = int(upper)
print("Example 5")
def next_guess(self):
if self.secret is not None:
return self.secret
while True:
guess = random.randint(self.lower, self.upper)
if guess not in self.guesses:
return guess
def send_number(self):
guess = self.next_guess()
self.guesses.append(guess)
self.send(format(guess))
print("Example 6")
def receive_report(self, decision):
last = self.guesses[-1]
if decision == CORRECT:
self.secret = last
print(f"Server: {last} is {decision}")
print("Example 7")
def clear_state(self):
self.lower = None
self.upper = None
self.secret = None
self.guesses = []
print("Example 8")
import contextlib
import time
@contextlib.contextmanager
def new_game(connection, lower, upper, secret):
print(
f"Guess a number between {lower} and {upper}!"
f" Shhhhh, it's {secret}."
)
connection.send(f"PARAMS {lower} {upper}")
try:
yield ClientSession(
connection.send,
connection.receive,
secret,
)
finally:
# Make it so the output printing matches what you expect
time.sleep(0.1)
connection.send("CLEAR")
print("Example 9")
import math
class ClientSession:
def __init__(self, send, receive, secret):
self.send = send
self.receive = receive
self.secret = secret
self.last_distance = None
print("Example 10")
def request_number(self):
self.send("NUMBER")
data = self.receive()
return int(data)
print("Example 11")
def report_outcome(self, number):
new_distance = math.fabs(number - self.secret)
if new_distance == 0:
decision = CORRECT
elif self.last_distance is None:
decision = UNSURE
elif new_distance < self.last_distance:
decision = WARMER
elif new_distance > self.last_distance:
decision = COLDER
else:
decision = SAME
self.last_distance = new_distance
self.send(f"REPORT {decision}")
return decision
print("Example 12")
def __iter__(self):
while True:
number = self.request_number()
decision = self.report_outcome(number)
yield number, decision
if decision == CORRECT:
return
print("Example 13")
import socket
from threading import Thread
def handle_connection(connection):
with connection:
session = ServerSession(connection)
try:
session.loop()
except EOFError:
pass
def run_server(address):
with socket.socket() as listener:
# Allow the port to be reused
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(address)
listener.listen()
while True:
connection, _ = listener.accept()
thread = Thread(
target=handle_connection,
args=(connection,),
daemon=True,
)
thread.start()
print("Example 14")
def run_client(address):
with socket.create_connection(address) as server_sock:
server = Connection(server_sock)
with new_game(server, 1, 5, 3) as session:
results = [outcome for outcome in session]
with new_game(server, 10, 15, 12) as session:
for outcome in session:
results.append(outcome)
with new_game(server, 1, 3, 2) as session:
it = iter(session)
while True:
try:
outcome = next(it)
except StopIteration:
break
else:
results.append(outcome)
return results
print("Example 15")
def main():
address = ("127.0.0.1", 1234)
server_thread = Thread(
target=run_server, args=(address,), daemon=True
)
server_thread.start()
results = run_client(address)
for number, outcome in results:
print(f"Client: {number} is {outcome}")
main()
print("Example 16")
class AsyncConnection:
def __init__(self, reader, writer): # Changed
self.reader = reader # Changed
self.writer = writer # Changed
async def send(self, command):
line = command + "\n"
data = line.encode()
self.writer.write(data) # Changed
await self.writer.drain() # Changed
async def receive(self):
line = await self.reader.readline() # Changed
if not line:
raise EOFError("Connection closed")
return line[:-1].decode()
print("Example 17")
class AsyncServerSession(AsyncConnection): # Changed
def __init__(self, *args):
super().__init__(*args)
self.clear_state()
print("Example 18")
async def loop(self): # Changed
while command := await self.receive(): # Changed
match command.split(" "):
case "PARAMS", lower, upper:
self.set_params(lower, upper)
case ["NUMBER"]:
await self.send_number() # Changed
case "REPORT", decision:
self.receive_report(decision)
case ["CLEAR"]:
self.clear_state()
case _:
raise UnknownCommandError(command)
print("Example 19")
def set_params(self, lower, upper):
self.clear_state()
self.lower = int(lower)
self.upper = int(upper)
print("Example 20")
def next_guess(self):
if self.secret is not None:
return self.secret
while True:
guess = random.randint(self.lower, self.upper)
if guess not in self.guesses:
return guess
async def send_number(self): # Changed
guess = self.next_guess()
self.guesses.append(guess)
await self.send(format(guess)) # Changed
print("Example 21")
def receive_report(self, decision):
last = self.guesses[-1]
if decision == CORRECT:
self.secret = last
print(f"Server: {last} is {decision}")
def clear_state(self):
self.lower = None
self.upper = None
self.secret = None
self.guesses = []
print("Example 22")
@contextlib.asynccontextmanager # Changed
async def new_async_game(connection, lower, upper, secret): # Changed
print(
f"Guess a number between {lower} and {upper}!"
f" Shhhhh, it's {secret}."
)
await connection.send(f"PARAMS {lower} {upper}") # Changed
try:
yield AsyncClientSession(
connection.send,
connection.receive,
secret,
)
finally:
# Make it so the output printing is in
# the same order as the threaded version.
await asyncio.sleep(0.1)
await connection.send("CLEAR") # Changed
print("Example 23")
class AsyncClientSession:
def __init__(self, send, receive, secret):
self.send = send
self.receive = receive
self.secret = secret
self.last_distance = None
print("Example 24")
async def request_number(self):
await self.send("NUMBER") # Changed
data = await self.receive() # Changed
return int(data)
print("Example 25")
async def report_outcome(self, number): # Changed
new_distance = math.fabs(number - self.secret)
if new_distance == 0:
decision = CORRECT
elif self.last_distance is None:
decision = UNSURE
elif new_distance < self.last_distance:
decision = WARMER
elif new_distance > self.last_distance:
decision = COLDER
else:
decision = SAME
self.last_distance = new_distance
await self.send(f"REPORT {decision}") # Changed
return decision
print("Example 26")
async def __aiter__(self): # Changed
while True:
number = await self.request_number() # Changed
decision = await self.report_outcome(number) # Changed
yield number, decision
if decision == CORRECT:
return
print("Example 27")
import asyncio
async def handle_async_connection(reader, writer):
session = AsyncServerSession(reader, writer)
try:
await session.loop()
except EOFError:
pass
async def run_async_server(address):
server = await asyncio.start_server(
handle_async_connection, *address
)
async with server:
await server.serve_forever()
print("Example 28")
async def run_async_client(address):
# Wait for the server to listen before trying to connect
await asyncio.sleep(0.1)
streams = await asyncio.open_connection(*address) # New
client = AsyncConnection(*streams) # New
async with new_async_game(client, 1, 5, 3) as session:
results = [outcome async for outcome in session]
async with new_async_game(client, 10, 15, 12) as session:
async for outcome in session:
results.append(outcome)
async with new_async_game(client, 1, 3, 2) as session:
it = aiter(session)
while True:
try:
outcome = await anext(it)
except StopAsyncIteration:
break
else:
results.append(outcome)
_, writer = streams # New
writer.close() # New
await writer.wait_closed() # New
return results
print("Example 29")
async def main_async():
address = ("127.0.0.1", 4321)
server = run_async_server(address)
asyncio.create_task(server)
results = await run_async_client(address)
for number, outcome in results:
print(f"Client: {number} is {outcome}")
logging.getLogger().setLevel(logging.ERROR)
asyncio.run(main_async())
logging.getLogger().setLevel(logging.DEBUG)