제너레이터 gen()이 yield from subgen()이 직접 호출자를 이끌고, gen()은 subgen()이 종료될 때까지 실행을 중단한다.
def gen():
for c in 'AB':
yield c
for i in range(1,3):
yield 1
list(gen())
#위의 코드 단축
def gen():
yield from 'AB'
yield from range(1,3)
#, yield from으로 반복형 객체 연결하기
def chain(*iterables):
for it in iterables:
yield from it
s = 'ABC'
t = tuple(range(3))
list(chain(s,t))
#yield from을 이용해서 averager()를 구동하고 보고서 생성
from collections import namedtuple
Result = namedtuple('Result','count average')
#하위
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)
#대표
def grouper(results, key):
while True:
results[key] = yield from averager()
#호출자
def main(data):
results = {}
for key, values in data.items():
group = grouper(results, key)
next(group)
for value in values:
group.send(value)
group.send(None)
return(results)
#실행 결과 보고서
def report(results):
for key, result in sorted(results.items()):
group, unit = key.split(';')
print('{:2} {:5} averaging {:.2f}{}'.format(
result.count,group,result.average,unit))