docs on for-loop with no __iter__?

Steven Bethard steven.bethard at gmail.com
Mon Sep 6 08:17:03 CEST 2004


Andrew Dalke <adalke <at> mindspring.com> writes:
> What I wanted was forward iteration
> in Python 1.x.  It happened that forward iteration was
> implemented only on top of indexing, so I had to hijack the
> indexing mechanism to get what I wanted.  But I never thought
> of it as "x[i] indexing" only "the hack needed to get forward
> iteration working correctly."

Good, that reaffirms my intuition that you didn't really want the __getitem__ 
behavior (eg x[i] access) -- it was just the only way to get the __iter__ 
behavior too.

Would it break old code if the __getitem__ iterator checked for a __len__ 
method and tried to use it if it was there?  It just seems like if you already 
know you're creating a sequence type and you have a __len__ and a __getitem__, 
then you've already provided all the necessary information for iteration.  Why 
should you have to define an __iter__ or throw IndexErrors in your __getitem__?

Steve




More information about the Python-list mailing list