여기서는 평균을 계산하는 또 다른 코루틴을 살펴본다. 이 버전은 중간 결과를 생성하지 않는
다. 대신 항목 개수와 평균을 담은 튜플을 반환한다. 코드는 [예제
17
-
40
]과 [예제
17
-
41
]의
두 부분으로 나누었다.
예제
17-40
coroaverager2
.
py
: 파일 앞부분
from collections.abc import Generator
from typing import Union, NamedTuple
class Result(NamedTuple): ❶
count: int # type: ignore ❷
average: float
class Sentinel: ❸
def __repr__(self):
return f’<Sentinel>’
STOP = Sentinel() ❹
SendType = Union[float, Sentinel] ❺
❶ [예제
17
-
41
]의
averager2
코루틴은
Result
형의 인스턴스를 반환한다.
❷
Result
는 사실
tuple
의 서브클래스로,
count
()
메서드가 있지만 우리에겐
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.