[Python-ideas] for/else syntax
Ron Adam
rrr at ronadam.com
Sat Oct 3 18:09:38 CEST 2009
Nick Coghlan wrote:
> Ron Adam wrote:
>> How about this?
>>
>> try:
>> for x in xs:
>> foo()
>> esle:
>> Print "foo didn't raise an exception."
>> except:
>> print "foo riased an exception"
>>
>> Using exceptions for flow control is very common in python.
>
> The else is adding no value here. That example would be better written as:
>
> try:
> for x in xs:
> foo()
> print "foo didn't raise an exception."
> except:
> print "foo riased an exception"
>
>> Or this:
>>
>> for x in xs:
>> y = foo()
>> if y is True:
>> return
>> else:
>> Print "y was never True"
>>
>> This is perfectly acceptable in my opinion.
>
> Again, using else here is redundant and misleading. The code is clearer
> if it is left out entirely:
>
> for x in xs:
> y = foo()
> if y is True:
> return
> print "y was never True"
>
> The *only* time an else clause is a better alternative to just writing
> the code after the loop is when there is a break statement present that
> may skip over it.
All good points. I need another cup of coffee. ;-)
There may be some obscure exception to the break-else pattern but I can't
think of any at the moment.
Considering the following...
>>> break
File "<stdin>", line 1
SyntaxError: 'break' outside loop
Documenting for/break/else patterns seems very appropriate.
+1
I suppose that it would have been clearer if it was for/then and
while/then. With a break stopping the loop, and skipping over the then block.
While it's much easer to explain that way, It adds a new keyword and isn't
something we could or should change now I suppose.
Cheers,
Ron
More information about the Python-ideas
mailing list