Re:Python 3.11: “Zero cost” exception handling
by openasocket on Wednesday October 06, 2021 @09:29AM
(#28772915)
When using a for-loop over an iterator, the iterator protocol in Python says to keep returning elements until you run out, at which point you throw an exception. So every loop over an iterator or iterable object in python throws an exception when it is done. https://docs.python.org/3/library/stdtypes.html#iterator.__n...
[ Parent
| on HN ]
Re:Python 3.11: “Zero cost” exception handling
by ynik on Wednesday October 06, 2021 @11:40AM
(#28774470)
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.