docs on for-loop with no __iter__?

Andrew Dalke adalke at mindspring.com
Sun Sep 5 01:43:33 EDT 2004
Steven Bethard wrote:
> 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?


The example I gave was for Python 1.x, which didn't support __iter__.
What I showed was how to support basic forward iteration (for use
in a for loop) in the old-days.

I used the assert check precisely so that the suggestion of
random access breaks when someone tries to use it that way.

> 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])?
> 
> (Obviously your FileReader class was an example of this, but I've assumed this 
> was just an example of how things *could* have been written, not how they 
> actually were.  Please correct me if I'm wrong!)

You say "x[i] indexing" but I don't think that's the right
way to frame the question.  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."

I wrote several classes using that technique.  One was a
way to read records from a file, another to get records from
from a database.  They worked, in that I could do things like

for record in FastaReader(open(filename)):
     print record.description

The new-style __iter__ is in all ways better.



				Andrew
				dalke at dalkescientific.com



More information about the Python-list mailing list