1# test user defined iterators
2
3# this class is not iterable
4class NotIterable:
5    pass
6try:
7    for i in NotIterable():
8        pass
9except TypeError:
10    print('TypeError')
11
12# this class has no __next__ implementation
13class NotIterable:
14    def __iter__(self):
15        return self
16try:
17    print(all(NotIterable()))
18except TypeError:
19    print('TypeError')
20
21class MyStopIteration(StopIteration):
22    pass
23
24class myiter:
25    def __init__(self, i):
26        self.i = i
27
28    def __iter__(self):
29        return self
30
31    def __next__(self):
32        if self.i <= 0:
33            # stop in the usual way
34            raise StopIteration
35        elif self.i == 10:
36            # stop with an argument
37            raise StopIteration(42)
38        elif self.i == 20:
39            # raise a non-stop exception
40            raise TypeError
41        elif self.i == 30:
42            # raise a user-defined stop iteration
43            print('raising MyStopIteration')
44            raise MyStopIteration
45        else:
46            # return the next value
47            self.i -= 1
48            return self.i
49
50for i in myiter(5):
51    print(i)
52
53for i in myiter(12):
54    print(i)
55
56try:
57    for i in myiter(22):
58        print(i)
59except TypeError:
60    print('raised TypeError')
61
62try:
63    for i in myiter(5):
64        print(i)
65        raise StopIteration
66except StopIteration:
67    print('raised StopIteration')
68
69for i in myiter(32):
70    print(i)
71
72# repeat some of the above tests but use tuple() to walk the iterator (tests mp_iternext)
73print(tuple(myiter(5)))
74print(tuple(myiter(12)))
75print(tuple(myiter(32)))
76try:
77    tuple(myiter(22))
78except TypeError:
79    print('raised TypeError')
80