In [10]:
def averager():
total = 0.0
count = 0
average = None
while True:
d = yield average
total +=d
count += 1
average = total / count
In [11]:
cor_avg = averager()
In [12]:
next(cor_avg)
In [14]:
cor_avg.send(12)
Out[14]:
In [17]:
from inspect import getgeneratorstate
In [21]:
from functools import wraps
def coroutine(func):
@wraps(func)
def primer(*args, **kwargs):
gen = func(*args, **kwargs)
next(gen)
return gen
return primer
In [16]:
coro_avg = averager()
In [18]:
getgeneratorstate(coro_avg)
Out[18]:
In [23]:
@coroutine
def averager():
total = 0.0
count = 0
average = None
while True:
d = yield average
total +=d
count += 1
average = total / count
In [24]:
coro_avg = averager()
In [25]:
getgeneratorstate(coro_avg)
Out[25]:
In [26]:
coro_avg.send(40)
Out[26]:
In [27]:
coro_avg.send(10)
Out[27]:
In [28]:
coro_avg.send('spam')
In [29]:
coro_avg.send(15)
In [33]:
class DemoException(Exception):
""""""
def demo_exc_handling():
print("-> coroutine started")
while True:
try:
x = yield
except DemoException: #<1>
print('*** DemoException handled.')
else:
print("-> coroutine received: {!r}".format(x))
raise RuntimeError('This line should never run.')
In [34]:
exc_coro = demo_exc_handling()
In [35]:
next(exc_coro)
In [37]:
exc_coro.send(11)
In [38]:
exc_coro.send(11)
In [40]:
exc_coro.throw(DemoException)
In [41]:
getgeneratorstate(exc_coro)
Out[41]:
In [ ]:
In [34]:
exc_coro = demo_exc_handling()
In [35]:
next(exc_coro)
In [37]:
exc_coro.send(11)
In [42]:
exc_coro.throw(ZeroDivisionError)
In [43]:
getgeneratorstate(exc_coro)
Out[43]:
In [ ]:
In [46]:
class DemoException(Exception):
""""""
def demo_finally():
print("-> coroutine started")
try:
while True:
try:
x = yield
except DemoException:
print("*** DemoException handled. Continuing...")
else:
print("->coroutine received: {!r}".format(x))
finally:
print("-> coroutine ending")
In [57]:
fin_coro = demo_finally()
In [58]:
next(fin_coro)
In [59]:
fin_coro.send(11)
In [60]:
fin_coro.send(12)
In [61]:
fin_coro.send("spam")
In [56]:
fin_coro.throw(ZeroDivisionError)
In [ ]:
In [62]:
from collections import namedtuple
In [64]:
Result = namedtuple('Result', 'count average')
In [65]:
def averager():
total = 0.0
count = 0
average = None
while True:
term = yield
if term is None:
break
total += term
count += 1
average = total/count
return Result(count, average)
In [66]:
coro_avg = averager()
In [67]:
next(coro_avg)
In [68]:
coro_avg.send(10)
In [69]:
coro_avg.send(20)
In [70]:
coro_avg.send(None)
In [ ]: