draft of coroutine examples

This commit is contained in:
Luciano Ramalho
2015-02-17 10:07:07 -02:00
parent dfb3c3b895
commit e910ec5458
13 changed files with 326 additions and 25 deletions

View File

@@ -45,7 +45,7 @@ Result = collections.namedtuple('Result', 'sum terms average')
def adder_coro(initial=0):
total = initial
num_terms = 0
count = 0
while True:
try:
term = yield total
@@ -54,8 +54,8 @@ def adder_coro(initial=0):
if term is None:
break
total += term
num_terms += 1
return Result(total, num_terms, total/num_terms)
count += 1
return Result(total, count, total/count)
def prompt():

View File

@@ -3,9 +3,13 @@ Closing a generator raises ``GeneratorExit`` at the pending ``yield``
>>> adder = adder_coro()
>>> next(adder)
0
>>> adder.send(10)
10
>>> adder.send(20)
30
>>> adder.send(30)
60
>>> adder.close()
-> total: 60 terms: 3 average: 20.0
@@ -14,7 +18,9 @@ Other exceptions propagate to the caller:
>>> adder = adder_coro()
>>> next(adder)
0
>>> adder.send(10)
10
>>> adder.send('spam')
Traceback (most recent call last):
...
@@ -25,13 +31,13 @@ Other exceptions propagate to the caller:
def adder_coro(initial=0):
total = initial
num_terms = 0
count = 0
try:
while True:
term = yield
term = yield total
total += term
num_terms += 1
count += 1
except GeneratorExit:
average = total / num_terms
average = total / count
msg = '-> total: {} terms: {} average: {}'
print(msg.format(total, num_terms, average))
print(msg.format(total, count, average))