아래 내용에는 필자가 잘못 이해하여 틀린 내용이 있을수도 있다.


https://mingrammer.com/translation-iterators-vs-generators/


yield가 뭐지?


python에서 yield문을 포함하는 함수는, 리턴값이 generator이다

generator는 iterator의 한 종류이다 (위 링크의 글 인용)


그리고 generator를 리턴하는 함수를 coroutine이라고 한다

코루틴이란, 함수의 일부만을 수행하고 suspend되는 함수이다

suspend되는 위치는 yield문까지이다


yield문을 통해 함수를 coroutine으로 만들 수 있다

coroutine을 왜 만들지?




coroutine의 장점?


함수를 coroutine으로 만들면, yield문의 위치에서의 동작을 함수 외부에 맡길 수 있다

callback 파라미터를 넘기는 것과의 차이는, 함수가 suspend된다는 점이다

(결국 suspend되기 때문에 임의 동작이 가능한 것이지만)


coroutine은, 함수를 일부분씩 실행할 수 있다는 장점이 있다



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def func():
    for i in range(10):
        print('func', i)
        yield i # yield and return i
 
def main():
    result = []
 
    for i in func():
        result.append(i)
 
    for i in result:
        print('result', i)
 
    
 
if __name__ == '__main__':
    main()
 
'''
# output
func 0
func 1
func 2
func 3
func 4
func 5
func 6
func 7
func 8
func 9
result 0
result 1
result 2
result 3
result 4
result 5
result 6
result 7
result 8
result 9
'''
 
cs


event = (yield) 문과 같이 함수 외부로부터 값을 받을수도 있다

이건 알아만 두자


'Language > python' 카테고리의 다른 글

[python] pip install whl file  (0) 2018.04.03
[python] SQLAlchemy  (0) 2018.04.03
[python] elasticsearch-py max_tries  (0) 2018.03.30
[python] 유용한 scrapy command  (0) 2018.03.29
[python] scrapy concurrent_requests  (0) 2018.03.27

WRITTEN BY
hojongs
블로그 옮겼습니다 https://hojongs.github.io/