This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Didn't raise "StopIteration" Error when I use "yield" in the function
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: SilentGhost, sheiun
Priority: normal Keywords:

Created on 2019-02-11 13:27 by sheiun, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
test.py sheiun, 2019-02-11 13:27 A test file to re-produce the problem.
Messages (3)
msg335215 - (view) Author: (sheiun) Date: 2019-02-11 13:27
Python 3.6.7 |Anaconda custom (64-bit)| (default, Oct 28 2018, 19:44:12) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def generate_loop():
...     for i in range(10):
...         print(i)
...         # should raise StopIteration when i > 5
...         k = next(j for j in range(5) if j == i)
...         print(k)
...         yield k
...
>>>
>>> def generate():
...     # should raise StopIteration
...     k = next(j for j in range(5) if j == 6)
...     yield k
...
>>>
>>> print(list(generate_loop()))
0
0
1
1
2
2
3
3
4
4
5
[0, 1, 2, 3, 4]
>>>
>>> print(list(generate()))
[]
>>>
>>> k = next(j for j in range(5) if j == 6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>
msg335216 - (view) Author: (sheiun) Date: 2019-02-11 13:31
But it still can catch by using try/except

>>> def generate_loop_stopiteration():
...     for i in range(10):
...         print(i)
...         # should raise StopIteration when i > 5
...         try:
...             k = next(j for j in range(5) if j == i)
...         except StopIteration:
...             print('catch')
...         print(k)
...         yield k
...
>>> print(list(generate_loop_stopiteration()))
0
0
1
1
2
2
3
3
4
4
5
catch
4
6
catch
4
7
catch
4
8
catch
4
9
catch
4
[0, 1, 2, 3, 4, 4, 4, 4, 4, 4]
>>>
msg335217 - (view) Author: SilentGhost (SilentGhost) * (Python triager) Date: 2019-02-11 13:46
Within a generator function, StopIteration exception is a sign that generator is finished. This is why this exception is caught automatically, and closes generator. This is normal and documented behaviour of generators.
History
Date User Action Args
2022-04-11 14:59:11adminsetgithub: 80147
2019-02-11 13:46:42SilentGhostsetstatus: open -> closed

type: behavior

nosy: + SilentGhost, sheiun
messages: + msg335217
resolution: not a bug
stage: resolved
2019-02-11 13:32:03sheiunsetnosy: - sheiun
-> (no value)
2019-02-11 13:31:49sheiunsetmessages: + msg335216
2019-02-11 13:27:49sheiuncreate