[Python-ideas] for/else syntax

Nick Coghlan ncoghlan at gmail.com
Sat Oct 3 17:17:35 CEST 2009


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.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list