I am trying to iterate over a class with __getitem__ , __len__. Sometimes the getitem might give a indexerror, but no exception is shown in the output. The program does not stop, only the loop breaks.
But When I access the items individually I do get the indexerror.
My question is why am I not getting the indexerror in forloop case.
Class Definition
class Abc:
a = [1,2,3,4]
def __len__(self):
return 4
def __getitem__(self,index):
if(index==2):
raise IndexError
return self.a[index]
Code-1
foo = Abc()
for y in foo:
print(y)
print("The End")
Output For Code-1
1
2
The End
Code 2
foo = Abc()
print(foo[1])
print(foo[2])
Output For Code 2:
2
Traceback (most recent call last):
File "test.py", line 14, in <module>
foo[2]
File "test.py", line 9, in __getitem__
raise IndexError
IndexError
test.py was filename
Note : The first comment answers the question.