Issue35966
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) * ![]() |
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:11 | admin | set | github: 80147 |
| 2019-02-11 13:46:42 | SilentGhost | set | status: open -> closed type: behavior nosy:
+ SilentGhost, sheiun |
| 2019-02-11 13:32:03 | sheiun | set | nosy:
- sheiun -> (no value) |
| 2019-02-11 13:31:49 | sheiun | set | messages: + msg335216 |
| 2019-02-11 13:27:49 | sheiun | create | |
