who uses Python or Ruby, and for what?

Thomas Bellman bellman at lysator.liu.se
Thu May 3 10:29:37 EDT 2001


"Fredrik Lundh" <fredrik at pythonware.com> writes:

> the iterator is the object that responds to __getitem__(lastindex+1),
> not the loop variable itself.

I think you should reread the section on the Iterator pattern in
"Design Patterns".  To follow the iterator pattern, the iterator
should be a *separate* object from the sequence that you are
iterating over.  (And if you don't have a copy of "Design
Patterns", you can come over and borrow mine; it's less than
100 meters. :-)

> (see fileinput for one example).

FileInput is an iterator, yes.  As is the objects returned by
xrange() (which iterates over the integral numbers) and the
.xreadlines() method of file objects.  For lists and tuples, the
loop variable *was* the iterator; for dictionaries there wasn't
any iterator.  Most other (user-defined) collection types I have
seen, didn't implement an Iterator, but only the __getitem__()
method, *on*the*collection*object*itself*; i.e all state about
the iteration was kept *inside* the collection object.

> well, a generic "use new-style iterator as forward sequence"
> wrapper is 10 lines, so it cannot be that hard...

As I said in my next paragraph:

>> Sure, you could *implement* iterators in Python, but that's
>> not the same as there *being* iterators.

> maybe not, but for something that doesn't exist, they've sure
> served me well over the last six years ;-)

The normal iteration API of old Python (old as in version 2.1 or
older, of course :-), i.e putting a __getitem__() method on the
collection type/class, *isn't* the Iterator pattern.  It's an
iteration API.  And an iteration API that works well in many,
probably even most, cases, but has certain limitations.  For
example, allowing efficient *concurrent* iteration over certain
types of collections (like linked lists, trees, hash tables).

You can easily implement the Iterator pattern, where the .next()
method on the iterator is spelled .__getitem__(lastindex+1),
removing those limitations.  But that isn't the normal iteration
API of older Python.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"I don't think [that word] means what you    !  bellman @ lysator.liu.se
 think it means."   -- The Princess Bride    !  Make Love -- Nicht Wahr!



More information about the Python-list mailing list