1# create a class that has a __getitem__ method
2class A:
3    def __getitem__(self, index):
4        print('getitem', index)
5        if index > 10:
6            raise StopIteration
7
8# test __getitem__
9A()[0]
10A()[1]
11
12# iterate using a for loop
13for i in A():
14    pass
15
16# iterate manually
17it = iter(A())
18try:
19    while True:
20        next(it)
21except StopIteration:
22    pass
23
24# this class raises an IndexError to stop the iteration
25class A:
26    def __getitem__(self, i):
27        raise IndexError
28print(list(A()))
29
30# this class raises a non-StopIteration exception on iteration
31class A:
32    def __getitem__(self, i):
33        raise TypeError
34try:
35    for i in A():
36        pass
37except TypeError:
38    print("TypeError")
39