python/응용
Coroutine yield 의 동작 이해
wefree
2023. 12. 13. 19:37
동작
- yield 는 기본 적으로 다음과 같은 순서로 동작한다.
- 값을 리턴한다. (즉시)
- 입력 값을 받기 위해 대기 한다.
- 최초 next() 나 send(None) 호출로 coroutine 을 시작한다. 처음 만나는 yield 도 위의 설명대로 동작한다.
코드
def simple_coroutine(a):
print(f"-> Started: {a=}")
b = yield a
print(f"-> Received: {b=}")
c = yield a + b
print(f"-> Received: {c=}")
my_coro = simple_coroutine(14)
next(my_coro)
# -> Started: a=14
# 14
my_coro.send(28)
# -> Received: b=28
# 42
my_coro.send(99)
# -> Received: c=99
# StopIteration Traceback (most recent call last)