[Python-Dev] Short-circuiting iterators

Raymond Hettinger raymond.hettinger at verizon.net
Wed Dec 7 01:58:10 CET 2005


[Matthew F. Barnes]  Perhaps it would be a useful addition to the
itertools
> module then?
> 
>         itertools.interruptable(iterable)

Any real-world use cases or compelling contrived examples?

ISTM, that the code calling it.stop() would already be in position to
break-out of the iteration directly or set a termination flag.  Instead
of:

    it = itertools.interruptable(iterable):
    for x in it:
        . . .
        if cond(x):
            it.stop()

Why not write:

    for x in iterable:
        . . .
        if cond(x):
            break

If needed, the for-loop can have an else-clause for any processing
needed in the event of interruption.



Raymond 



More information about the Python-Dev mailing list