[Python-Dev] Short-circuiting iterators

Matthew F. Barnes mfb at lotusland.dyndns.org
Wed Nov 30 19:40:26 CET 2005


I've not had much luck in searching for a discussion on this in the
Python-Dev archives, so bear with me.

I had an idea this morning for a simple extension to Python's iterator
protocol that would allow the user to force an iterator to raise
StopIteration on the next call to next().  My thought was to add a new
method to iterators called stop().

In my situation it would be useful as a control-flow mechanism, but I
imagine there are many other use cases for it:

    generator = some_generator_function()

    for x in generator:
        ... deeply ...
            ... nested ...
                ... control-flow ...

                    if satisfaction_condition:
                        # Terminates the for-loop, but
                        # finishes the current iteration

        ... more stuff ...

I'm curious if anything like this has been proposed in the past.  If so,
could someone kindly point me to any relevant mailing list threads?

Matthew Barnes

More information about the Python-Dev mailing list