Dangerous behavior of list(generator)
Martin v. Loewis
martin at v.loewis.de
Sat Jan 2 15:27:54 EST 2010
> I'm asking about why the behavior of a StopIteration exception being
> handled from the `expression` of a generator expression to mean "stop
> the loop" is accepted by "the devs" as acceptable.
I may be late to this discussion, but the answer is "most definitely
yes". *Any* exception leads to termination of the iterator, and
StopIteration is no different:
py> def stop(e):
... def f():
... raise e
... return f
...
py> g = (f() for f in (lambda:1,stop(StopIteration),lambda:2))
py> g.next
<method-wrapper 'next' of generator object at 0xb7960fac>
py> g.next()
1
py> g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
File "<stdin>", line 3, in f
StopIteration
py> g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
py> g = (f() for f in (lambda:1,stop(ValueError),lambda:2))
py> g.next()
1
py> g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
File "<stdin>", line 3, in f
ValueError
py> g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Regards,
Martin
More information about the Python-list
mailing list