Looking for doh!.. simple sequence type

Steffen Kirschke steffen at molli15.org
Sat Apr 13 12:50:58 EDT 2002


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,raise StopIteration
> 
>  >>>42 42 42 42

--<schnipp>--

class Lst:
        def __init__(self):
                self.iter = 0
                self.len = 4

        def __getitem__(self,key):
                if self.iter == self.len:
                        self.iter = 0
                        raise StopIteration
                else:
                        self.iter += 1
                        return 'The answer'


or, instead of __getitem__

        def __iter__(self):
                self.iter = 0
                return self

        def next(self):
                if self.iter == self.len:
                        raise StopIteration
                else:
                        self.iter += 1
                        return 42
--<schnapp>--

The second one works afaik from 2.2 up only..

hth

Steffen




More information about the Python-list mailing list