4 ms·
While that's true at the Python language level, there are already special optimizations for this in CPython: `tp_iternext` is not required to set an exception.
by ynik 5y ago
While that's true at the Python language level, there are already special optimizations for this in CPython: `tp_iternext` is not required to set an exception. If it returns NULL without setting an exception, that's taken to be the end of iteration.
If you call `next()` in Python, this special case is translated to a `StopIteration` exception.
But if you use a for-loop, it can directly stop iterating without ever materializing the `StopIteration` exception. So the overhead of Python raise/try-except is already irrelevant for the for-loop.