LoginSignup
10
9

More than 5 years have passed since last update.

python3x: returnとyieldの違い

Last updated at Posted at 2017-05-05

前に書いたimpure function and pure function、difference between print and returnでは主にprintreturnの違いを書いたが今回はreturnyieldの違いについてまとめておく。

return vs yield

returnは処理制限を返している

忘れないようにここでreturnyieldの違いを載せておく。そもそも通常の関数ならば一度returnexceptionもしくは最後の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
10
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9