docs on for-loop with no __iter__?

Just just at xs4all.nl
Sun Sep 5 01:26:00 EDT 2004


In article <mailman.2883.1094340967.5135.python-list at python.org>,
 Steven Bethard <steven.bethard at gmail.com> wrote:

> Andrew Dalke <adalke <at> mindspring.com> writes:
> > Steven Bethard wrote:
> > > Presumably there was a reason not to use len() to determine
> > > the end of the sequence?
> > 
> > Because that allows iteration over things where
> > you don't yet know the size.
> 
> I'm trying to imagine a situation where it makes sense to want the x[i] 
> behavior from __getitem__ but where you don't know the final index.  x[i] 
> suggests random access, so if you don't really have random access, shouldn't 
> you be defining __iter__ instead?  Are there some good examples of classes 
> that allow the x[i] indexing but don't support random access (e.g. you can do 
> only do x[2] after you do x[1])?

You're looking at it from a wrong totally wrong direction. The iterator 
protocol did not exist prior to Python 2.2, and "__getitem__ iteration" 
was the only way to implement custom iteration behavior. Its 
limitiations were (I think) a major incentive to create something 
better. In fact, the "new" iteration protocol is so brilliant, obvious 
and simple, that it's hard to see how we ever did without it, or even 
why noone invented it earlier...

In other words: you're looking at a legacy protocol.

Just



More information about the Python-list mailing list