StopIteration in the if clause of a generator expression
Peter Otten
__peter__ at web.de
Sun Apr 3 04:15:17 EDT 2005
jfj wrote:
>> To make it a bit clearer, a StopIteration raised in a generator
>> expression silently terminates that generator:
>
> *any* exception raised from a generator, terminates the generator
Yeah, but StopIteration is the only expected exception and therefore the
only one that client code (nearly) always knows to deal with:
>>> def choke(): raise ValueError
...
>>> list(i for i in range(10) if i < 3 or choke())
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in <generator expression>
File "<stdin>", line 1, in choke
ValueError
>>> [i for i in range(10) if i < 3 or choke()]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in choke
ValueError
Here you can *not* tell apart list(genexp) and listcomp.
(Of course, as has since been pointed out, the StopIteration is actually
caught in the list constructor, so nothing magic to the example in my
initial post)
Peter
More information about the Python-list
mailing list