Use-cases for alternative iterator

Terry Reedy tjreedy at udel.edu
Fri Mar 11 15:14:56 EST 2011


On 3/11/2011 1:43 AM, Steven D'Aprano wrote:
> The iter() built-in takes two different forms, the familiar
> iter(iterable) we all know and love, and an alternative form:
>
> iter(callable, sentinel)

> E.g.:
>
>>>> T = -1
>>>> def func():
> ...     global T
> ...     T += 1
> ...     return T
> ...
>>>> it = iter(func, 3)
>>>> next(it)
> 0
>>>> next(it)
> 1
>>>> next(it)
> 2
>>>> next(it)
> Traceback (most recent call last):
>    File "<stdin>", line 1, in<module>
> StopIteration
>
>
>
> I've never seen this second form in actual code. Does anyone use it, and
> if so, what use-cases do you have?

Looking through Peter's nice list of real use cases, I see two 
categories: adapting an iterator-like function to Python's protocol; 
stopping an iterator before its normal exhaustion.

An example of the latter: suppose a file consists of header and body 
separated by a blank line. An opened file is an iterable, but its 
iterator only stops at eof. To process the two parts separately (using 
example from Peter's list):

for l in iter(f.readline,''):
   <process header line>
for l in f:
   <process body line>

(I am pretty sure that there are no buffer screwups with stop and 
restart since f iterator should call f.readline internally.)
Alternative is explicit "if l == '': break" in first loop.

I suspect the two param form, still rather new and unusual, is used less 
that is could, and perhaps should be. I am glad you raised the question 
to get me thinking about it.

-- 
Terry Jan Reedy




More information about the Python-list mailing list