Looking for doh!.. simple sequence type
Quinn Dunkan
quinn at regurgitate.ugcs.caltech.edu
Fri May 10 16:46:43 EDT 2002
On Fri, 12 Apr 2002 13:02:48 +0200, Max M <maxm at mxm.dk> 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.
'for X in Y' doesn't use __len__, it just keeps calling __getitem__ until it
gets an IndexError.
def __getitem__(self, i):
if 0 > i >= 4: # one of python's fun little obscure features
raise IndexError
else:
return 42
Langref 7.3 says "An internal counter is used to keep track of which item is
used next, and this is incremented on each iteration. When this counter has
reached the length of the sequence the loop terminates." which is misleading.
In 2.2 'for X in Y' calls Y.__iter__, so the protocol is totally different but
nicer.
More information about the Python-list
mailing list