[Python-Dev] PEP 3142: Add a "while" clause to generator expressions

Calvin Spealman ironfroggy at gmail.com
Tue Jan 20 18:54:03 CET 2009


On Tue, Jan 20, 2009 at 12:46 PM, Gerald Britton
<gerald.britton at gmail.com> wrote:
> I wonder if this is a bug?

I don't think so, but its interesting nonetheless.

passing a generator expression to list() involves two loops: the list
construction and the generator expression. So, a StopIteration from
whatever the GE is iterating over is caught by the GE mechanics, and
anything else in the clauses can be caught by the list constructor.

If the same thing is done in a LC, such an exception from the clause
has nothing to catch it. It is not raised as part of iterating over
something. I don't think we'd want to just start swallowing errors
here, as it would change defined behavior.

> On Tue, Jan 20, 2009 at 11:32 AM, Vitor Bosshard <algorias at yahoo.com> wrote:
>> ----- Mensaje original ----
>>> De: "python-3000 at udmvt.ru" <python-3000 at udmvt.ru>
>>> Para: Gerald Britton <gerald.britton at gmail.com>
>>> CC: python-dev at python.org
>>> Enviado: martes, 20 de enero, 2009 11:18:24
>>> Asunto: Re: [Python-Dev] PEP 3142: Add a "while" clause to generator expressions
>>>
>>> May I suggest you this variant?
>>>
>>>     def raiseStopIteration():
>>>         raise StopIteration
>>>
>>>     g = (n for n in range(100) if n*n < 50 or raiseStopIteration())
>>>
>>> Well, there are more characters...
>>>
>>> But it is not using any syntax changes and does not require any approval
>>> to be functional. Yet it is as fast as the proposed variant, does not require
>>> modules and, I hope, will not confuse you or anyone else.
>>>
>>
>> This works as a generator, but not as a list comprehension. The exception is propagated instead of just cutting short the loop:
>>
>>>>> def r(): raise StopIteration
>>>>> print [i for i in range(10) if i**2 < 50 or r()]
>> Traceback (most recent call last):
>>   File "<pyshell#2>", line 1, in <module>
>>     print [i for i in range(10) if i**2 < 50 or r()]
>>   File "<pyshell#1>", line 1, in r
>>     def r(): raise StopIteration
>> StopIteration
>>>>>
>>
>>
>> Vitor
>>
>>
>>      ¡Todo sobre la Liga Mexicana de fútbol! Estadisticas, resultados, calendario, fotos y más:<
>> http://espanol.sports.yahoo.com/
>>
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: http://mail.python.org/mailman/options/python-dev/ironfroggy%40gmail.com
>



-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://techblog.ironfroggy.com/
Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy


More information about the Python-Dev mailing list