[Python-ideas] if condition: break idiom

Carl Johnson carl at carlsensei.com
Sun Sep 21 06:06:27 CEST 2008


> An alternate construct could be something like:
>
> """
> def While(x):
>  if x > 10:
>    return None
>  else:
>    return x
>
> [w for w in (While(x) for x in range(20)) if w is not None]
> """

The problem is that this version won't work if range(20) is replaced  
with itertools.count() or any other non-finite generator, whereas the  
raise Break version will.

Another nice thing about using raise for loop control is that "raise  
Continue" can be used to skip elements:

def even(x):
     if x % 2:
         raise Continue
     else:
         return x

[even(x) for x in range(10)] # [0, 2, 4, 6, 8]

This would have to be broken in two parts to do in current Python (and  
indeed, that might be the chief advantage of *not* adopting my  
proposal--TOOWTDI):

def even(x):
     return not x % 2

[x for x in range(10) if even(x)]

As for beginners in Python, I don't think learning to use "raise  
Continue" instead of "continue" will really be that hard. I think the  
main reason to reject my proposal is that complicated loops shouldn't  
be done in list comprehensions at all. They should be written out,  
like reduce expressions. Still, it might be convenient in some cases,  
and it would be a good chance to cut out unnecessary keywords.

-- Carl




More information about the Python-ideas mailing list