Re: [Python-Dev] why not "return StopIteration"?
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 prematurely. 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/)
"GvR" == Guido van Rossum <guido@digicool.com> writes:
| - 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. Plus, if the exception is both raised and caught in C, it is never instantiated, so exception matching is a pointer compare. I know this isn't the case with user defined iterators (since Python's raise semantics is to instantiate the exception), but it helps. -Barry
participants (3)
-
barry@digicool.com
-
Guido van Rossum
-
Neil Schemenauer