4

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.

  • 5
    "Note for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence." - https://docs.python.org/3/reference/datamodel.html#object.__getitem__ – Blorgbeard Apr 02 '19 at 23:32

0 Answers0