docs on for-loop with no __iter__?

Andrew Dalke adalke at mindspring.com
Sat Sep 4 16:41:43 EDT 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...

http://docs.python.org/ref/sequence-types.html

] 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 docs.python.org
for __getitem__ and IndexError )

Looking at the language reference from CVS, I found
  http://www.python.org/dev/doc/devel/ref/for.html

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?

				Andrew
				dalke at dalkescientific.com



More information about the Python-list mailing list