forked from fluentpython/example-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoroaverager.py
More file actions
45 lines (38 loc) · 977 Bytes
/
coroaverager.py
File metadata and controls
45 lines (38 loc) · 977 Bytes
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
"""
Closing a generator raises ``GeneratorExit`` at the pending ``yield``
>>> coro_avg = averager()
>>> next(coro_avg)
0.0
>>> coro_avg.send(10)
10.0
>>> coro_avg.send(20)
15.0
>>> coro_avg.send(30)
20.0
>>> coro_avg.close()
-> total: 60.0 average: 20.0 terms: 3
Other exceptions propagate to the caller:
>>> coro_avg = averager()
>>> next(coro_avg)
0.0
>>> coro_avg.send(10)
10.0
>>> coro_avg.send('spam')
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +=: 'float' and 'str'
"""
# BEGIN CORO_AVERAGER
def averager():
total = average = 0.0
count = 0
try:
while True:
term = yield average
total += term
count += 1
average = total/count
except GeneratorExit:
msg = '-> total: {} average: {} terms: {}'
print(msg.format(total, average, count))
# END CORO_AVERAGER