docs on for-loop with no __iter__?

Andrew Dalke adalke at
Sat Sep 4 22:41:43 CEST 2004

Steven Bethard wrote:
> Can someone point me to the documentation on what's supposed to happen
> when you use the "for x in X:" syntax when X does not have an __iter__
> method?

You need to raise an IndexError

> ....     def __len__(self): return 42
> ....     def __getitem__(self, i): return i

Make that say

def __getitem__(self, i):
     if i >= 42: raise IndexError, i
     return i

> Obviously, the right
> way to do this is with __iter__, but presumably this behavior is
> documented somewhere...

] Note: for loops expect that an IndexError will be
] raised for illegal indexes to allow proper detection
] of the end of the sequence.

That's all I can find in the docs (searched
for __getitem__ and IndexError )

Looking at the language reference from CVS, I found

It states

]  The suite is then executed once for each item in
] the sequence, in the order of ascending indices.

That implies the sequence is indexed, yes?  But if
the sequence implements __iter__ then there's no
possibly no underlying idea of 'index'.

Should this be fixed?

				dalke at

More information about the Python-list mailing list