python/응용

yield from

wefree 2023. 4. 10. 20:46

https://medium.com/better-programming/a-hands-on-guide-to-concurrency-in-python-with-asyncio-af33a795d808 참고

 

def get_all_numbers():
    yield 1
    yield from get_some_numbers()
    yield 5

def get_some_numbers():
    yield 2
    yield 3
    yield 4

for i in get_all_numbers():
    print(i)

>> 1
>> 2
>> 3
>> 4
>> 5

 

Coroutines are defined using the async def keyword and can use the await syntax inside. The await keyword is very similar to yield from — it turns the control over to another function and tells the caller that it now has to wait for it to complete.

 

 

다른 예제

coroutine 에서 사용

def s_hello():
    yield "hello 1"
    yield "hello 2"
    return "done"
    

def g_hello():
    # while True:
    r = yield from s_hello()
    yield r

g = g_hello()

for x in g:
    print(x)


> hello 1
> hello 2
> done

s_hello() 마지막에 return "done" 이 없으면, 출력 결과로 done 대신에 None 이 나온다.