Help us understand the problem. What is going on with this article?

Python 3.7 ではGeneretor で StopIteration を使うと RuntimeError になる

More than 1 year has passed since last update.

次のコードはPython 3.7で実行すると RuntimeError になります。

def tentimes():
    i = 0
    while True:
        if i == 10:
            raise StopIteration
        yield i
        i = i + 1


for i in tentimes():
    print(i)
0
1
2
3
4
5
6
7
8
9
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-1-20f0585f0e57> in tentimes()
      4         if i == 10:
----> 5             raise StopIteration
      6         yield i

StopIteration:

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
<ipython-input-2-ade91eb5a83d> in <module>
----> 1 for i in tentimes():
      2     print(i)
      3

RuntimeError: generator raised StopIteration

これは組み込み例外 — Python 3.7.3 ドキュメント に記述があり、PEP 479 -- Change StopIteration handling inside generators がデフォルトで有効化されているためです。

同様のコードは次のように修正すると動きます。

def tentimes():
    i = 0
    while True:
        if i == 10:
            return
        yield i
        i = i + 1


for i in tentimes():
    print(i)    
0
1
2
3
4
5
6
7
8
9

Pythonのイテレータとジェネレータ - Qiitaの記事にあるような実装で raise StopIteration しても RuntimeError にはなりません。

class MyRange(object):
    def __init__(self, start, end):
        self._i = start
        self._end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self._i == self._end:
            raise StopIteration
        value = self._i
        self._i = self._i + 1
        return value

my_range = MyRange(0, 10)
for i in my_range:
    print(i)
0
1
2
3
4
5
6
7
8
9
repro
世界59か国6,500以上の導入実績を持つCE(カスタマーエンゲージメント)プラットフォーム「Repro(リプロ)」を提供
https://repro.io/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした