Looking for doh!.. Answer found

Max M maxm at mxm.dk
Fri Apr 12 08:00:36 EDT 2002


Answer found:

The problem is that __getitem__ doesn't check length.  Instead, it
terminates on an IndexError exception.

class Lst:
     def __getitem__(self, idx):
         if idx>=4:
             raise IndexError
         else:
             return 42

lst = Lst()
for i in lst:
     print i

42
42
42
42


Max M wrote:
> Hmm ... I am trying to create a simple sequence type that I cant iterate 
> over like (Python 2.1)::
> 
> lst = Lst()
> for i in lst:
>     print i
> 
> And I thought I could do it like:
> 
> class Lst:
> 
>     def __len__(self):
>         return 4
> 
>     def __getitem__(self, idx):
>         return 42
> 
> But I have to write it like below to avoid an endless loop..
> 
> lst = Lst()
> for i in range(len(lst)):
>     print i,
> 
>  >>>42 42 42 42
> 
> I am shure it's so simple tha I will go Doh! .. But perhaps I haven't 
> had enough cofee yet. 'Cause I cannot seem to figure it out.
> 
> regards Max M
> 




More information about the Python-list mailing list