summaryrefslogtreecommitdiffstatshomepage
path: root/tests/basics/iter1.py
blob: c2ef86a6356b5771972f567d065df1b112290b86 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# test user defined iterators

class MyStopIteration(StopIteration):
    pass

class myiter:
    def __init__(self, i):
        self.i = i

    def __iter__(self):
        return self

    def __next__(self):
        if self.i <= 0:
            # stop in the usual way
            raise StopIteration
        elif self.i == 10:
            # stop with an argument
            raise StopIteration(42)
        elif self.i == 20:
            # raise a non-stop exception
            raise TypeError
        elif self.i == 30:
            # raise a user-defined stop iteration
            print('raising MyStopIteration')
            raise MyStopIteration
        else:
            # return the next value
            self.i -= 1
            return self.i

for i in myiter(5):
    print(i)

for i in myiter(12):
    print(i)

try:
    for i in myiter(22):
        print(i)
except TypeError:
    print('raised TypeError')

try:
    for i in myiter(5):
        print(i)
        raise StopIteration
except StopIteration:
    print('raised StopIteration')

for i in myiter(32):
    print(i)