[Python-iterators] Re: [Python-Dev] Shall I start adding iterators to Python 2.2?

Thomas Wouters thomas@xs4all.net
Fri, 20 Apr 2001 11:26:38 +0200


On Fri, Apr 20, 2001 at 11:02:09AM +0200, M.-A. Lemburg wrote:

> > - There's an operation to create an iterator from a function and a
> >   sentinel value.  This is spelled as iter(function, sentinel).  For
> >   example,
> > 
> >     for line in iter(sys.stdin.readline, ""):
> >       ...
> > 
> >   is an efficient loop over the lines of stdin.

> Hmm, I guess you have to compare each function output to the
> sentinel then, right ? This can be very expensive.

> Wouldn't an exception base class also do the trick as sentinel ? The 
> iterator would then stop when an exception is raised by the
> function which matches the sentinel exception.

The sentinel method is for use with existing functions, that return a
sentinel value (like "" or None or whatever.) Comparing to those is not
terribly expensive, asside from the burden of running a single compare in
the inner loop. Rewriting those functions to raise an exception instead
would be, well, somewhat silly -- if you're rewriting them anyway, why not
just make an iterator out of them ?

-- 
Thomas Wouters <thomas@xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!