前に書いたimpure function and pure function、difference between print and returnでは主にprint
とreturn
の違いを書いたが今回はreturn
とyield
の違いについてまとめておく。
return vs yield
returnは処理制限を返している
忘れないようにここでreturn
とyield
の違いを載せておく。そもそも通常の関数ならば一度return
かexception
もしくは最後のreturn None
を通過すると同時に役目を終える。その関数に含まれていたローカル変数に関する情報は全て消えてしまう。つまり
return implies that the function is returning control of execution to the point where the function is called. returnは処理結果を関数が呼ばれたところに戻している。リターンしているのでreturn。
returnは関数の出口のお手伝いと処理結果の受け渡しをしてくれているというイメージ。
def foo():
a = 1
b = 2
return a #ここで処理を終えてaを返す
c = 3
return b
yieldは関数内の情報を記録したまま処理を行う
これはこれで便利なのだがもし仮に「関数内の情報をそのまま記録したまま処理を行いたい」場合はどうしようか。例えば「必要に応じて奇数を返してくれる関数が欲しい!」とか「素数を順番に一つずつ出してくれる関数が欲しい」など。
"Yield," however, implies that the transfer of control is temporary and voluntary. しかしyieldは処理結果の受け渡しが一時的、かつ任意的である。関数の処理制限が必ずしも関数が呼ばれたところに戻るわけではないということ。
def generator():
print("Starting here")
i = 0
while i < 6:
print("Before yield")
yield i
print("After yield")
i += 1
>>> g = generator()
>>> g
<generator object generator at 0x106c1e9e8>
>>> next(g)
Starting here
Before yield
0
>>> next(g)
After yield
Before yield
1