'Why doesn't this code raise a StopIteration exception?
In this code I have class name Iter that contains Two dunder methods __iter__ and __next__. In __iter__method I set self.current equal to zero and return self. In next method I increase
self.current += 1. When it reaches 10 I want it to raise a StopIteration exception.
class Iter:
def __iter__(self):
self.current = 0
return self
def __next__(self):
self.current += 1
if self.current == 10:
raise StopIteration
return self.current
it = Iter()
for i in it:
print(i)
Solution 1:[1]
Your iterator already raises StopIteration, which is caught by the for loop in order to stop the iteration. This is just how for loops work normally.
You can see this easily in your iterator if you add a print:
def __next__(self):
self.current += 1
if self.current == 10:
print("raising StopIteration")
raise StopIteration
1
2
3
4
5
6
7
8
9
raising StopIteration
If you want to re-raise StopIteration after your iterator is exhausted, one option is just to raise one manually after the for loop:
it = Iter()
for i in it:
print(i)
raise StopIteration
1
2
3
4
5
6
7
8
9
Traceback (most recent call last):
File "test.py", line 16, in <module>
raise StopIteration
StopIteration
Another is to change the way you do the iteration so that the StopIteration isn't caught:
it = iter(Iter())
while True:
print(next(it))
1
2
3
4
5
6
7
8
9
Traceback (most recent call last):
File "test.py", line 15, in <module>
print(next(it))
File "test.py", line 9, in __next__
raise StopIteration
StopIteration
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samwise |
