return 的作用
在一個 generator function 中,如果沒有 return,則默認執行至函數完畢,如果在執行過程中 return,則直接拋出 StopIteration 終止迭代。
def func():
a = 0
b = 1
while True:
if b >= 5:
return
yield b
a, b = b, a + b
f = func()
while True:
print(next(f))
# 結果:
# 1
# 1
# 2
# 3
# ---------------------------------------------------------------------------
# StopIteration Traceback (most recent call last)
# <ipython-input-4-3a2f06d59b2d> in <module>
# 9 f = func()
# 10 while True:
# ---> 11 print(next(f))
#
# StopIteration:
所以,想要使for迭代終止,可以在generator function中使用兩種方式,一種是while+條件,第二種就是使用return語句。
return方式:
def func():
a = 0
b = 1
while True:
# 當b等於5時終止
if b >= 5:
return
yield b
a, b = b, a + b
f = func()
for i in f:
print(i)
1
1
2
3
while+條件:
def func(max):
n = 0
a = 0
b = 1
while n < max:
yield b
a, b = b, a + b
n += 1
f = func(3)
for i in f:
print(i)
1
1
2
用yield讀大文件:
def read_file(fpath):
BLOCK_SIZE = 1024
with open(fpath, 'rb') as f:
while True:
block = f.read(BLOCK_SIZE)
if block:
yield block
else:
return