Looking for doh!.. simple sequence type

Ken Seehof kseehof at neuralintegrator.com
Fri Apr 12 07:59:22 EDT 2002


Ken wrote:
> 
> Max 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
> > 
> 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

What I meant to say is that the default __iter__ doesn't check length,
but does a __getitem__ until it terminates on an IndexError exception.

Best regards,
- Ken






More information about the Python-list mailing list