简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM