[Python-Dev] why not "return StopIteration"?

Guido van Rossum guido@digicool.com
Fri, 22 Jun 2001 12:19:34 -0400

This is treated extensively in the discussion section of the
iterators-PEP; quoting:

    - It has been questioned whether an exception to signal the end of
      the iteration isn't too expensive.  Several alternatives for the
      StopIteration exception have been proposed: a special value End
      to signal the end, a function end() to test whether the iterator
      is finished, even reusing the IndexError exception.

      - A special value has the problem that if a sequence ever
        contains that special value, a loop over that sequence will
        end prematurely without any warning.  If the experience with
        null-terminated C strings hasn't taught us the problems this
        can cause, imagine the trouble a Python introspection tool
        would have iterating over a list of all built-in names,
        assuming that the special End value was a built-in name!

      - Calling an end() function would require two calls per
        iteration.  Two calls is much more expensive than one call
        plus a test for an exception.  Especially the time-critical
        for loop can test very cheaply for an exception.

      - Reusing IndexError can cause confusion because it can be a
        genuine error, which would be masked by ending the loop

I'm not sure why you are reopening this -- special terminating values
are evil IMO. :-)

--Guido van Rossum (home page: http://www.python.org/~guido/)