wtfpython
wtfpython copied to clipboard
StopIteration sometimes gets transformed to RuntimeError (PEP 0479)
next on an empty iter raises StopIteration
>>> next(iter([]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
And if you do this in a list comprehension you get the same error
>>> x, y = [next(iter(z)) for z in ([], [])]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
StopIteration
But if you change list comprehension to a generator expression then the exception type is transformed!
>>> x, y = (next(iter(z)) for z in ([], []))
Traceback (most recent call last):
File "<stdin>", line 1, in <genexpr>
StopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: generator raised StopIteration
This is new behavior as of Python 3.5 https://peps.python.org/pep-0479/