Endless loop

Ulrich Eckhardt doomster at knuut.de
Sat Jan 2 08:21:27 EST 2010


vsoler wrote:
> class stepper:
>     def __getitem__(self, i):
>         return self.data[i]
> 
> X=stepper()
> X.data="Spam"
> for item in X:
>     print item,
> 
> ... what I get is     S p a m     which seems logical to me since the
> loop stops after the 4th character.

I think you're mistaking the cause and effect here, see below.

> class stepper:
>     def __getitem__(self, i):
>         return i
> 
> X=stepper()
> X.data="Spam"
> for item in X:
>     print item,
> 
> ... what I get is an endless loop, starting at zero:    0 1 2 3 4 5 6
> 7 8 9 10 11  and so on.
> 
> My question is: why does this second script not stop after printing
> number 3?  what made the first one stop while the second one will not?

First thing to observe in the second case is that X's data field is not used 
anywhere. The field is set and then not used any further. In particular, it 
is not used to somehow get the length of the sequence to return.

Now, "spam"[4] will raise an IndexError, thus terminating the iteration. The 
second implementation which only returns the index never will do that, so 
the iteration never stops.

Uli




More information about the Python-list mailing list