[Python-ideas] if condition: break idiom

Brett Cannon brett at python.org
Sun Sep 21 06:34:16 CEST 2008


On Sat, Sep 20, 2008 at 9:09 PM, Ron Adam <rrr at ronadam.com> wrote:
>
>
> Carl Johnson wrote:
>>
>> Slightly OT, but I think 'break' and 'continue' should be replaced with
>> 'raise Break' and 'raise Continue' in Python 4000, just as we 'raise
>> StopIteration' in generators today. This would be handy, because you could
>> use it in functions called by a list comprehension:
>>
>> def while(x):
>>    if x > 10:
>>        raise Break
>>    else:
>>        return x
>>
>> [while(x) for x in range(20)]  #produces [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
>> 10]
>>
>> Right now, you can do something this with list(generator expression) by
>> raising StopIteration, but it is considered a hack, and it doesn't work with
>> list comprehensions.
>
> Maybe break should raise a StopIteration and continue should raise
> NextIteration?
>
> What would be the effect on performance to for and while loops?
>

You would have to essentially make loops syntactic sugar for
try/except statements. And if you had StopIteration and NextIteration
you would have to have a nested try/except::

try:
  LOOP:
    ... loop stuff ...
   try:
     ... loop body ...
   except NextIteration:
     pass
    goto LOOP
except StopIteration:
  pass

Exceptions are not expensive, but they are not exactly a no-op either.

-Brett



More information about the Python-ideas mailing list