[Python-ideas] for/else statements considered harmful

Terry Reedy tjreedy at udel.edu
Sat Jun 9 01:59:46 CEST 2012

> Devin Jeanpierre wrote:
>> I've never been sure of what is good style here. It's comparable to
>> these two things:
>> def foo():
>> if bar():
>> return baz
>> return quux
>> def foo2():
>> if bar():
>> return baz
>> else:
>> return quux
>> Is there some well-accepted rule of which to use?

The rule I have adopted is to omit unneeded after-if else to separate 
preamble stuff -- argument checking -- from the core algorithm, but 
leave it when branching is an essential part of the algorithm. My idea 
is that if the top level structure of the algorithm is an alternation, 
then the code should say so without the reader having to examine the 
contents of the branch.

Example: floating-point square root

def fsqrt(x):
   if not isinstance(x, float):
     raise TypeError
   elif x < 0:
     raise ValueError
   # Now we are ready for the real algorithm
   if x > 1.0:
     return fsqrt(1/x)
     # iterate
     return result

Omission of elses can definitely be taken too far. There is in the C 
codebase code roughly with this outline:

if expression:
   # about 15 line with at least 2 nested ifs (with else omitted)
   # and at least 3 codepaths ending in return
calculation for else but with else omitted

It takes far longer for each reader to examine if block to determine the 
the following block is really an else block that it would have taken one 
writer to just put in the "} else {"

Also, some editor allow collapsing of indented blocks, but one cannot do 
that if else is omitted.

Of course, it is routine to omit unneeded else after loops.

Terry Jan Reedy

More information about the Python-ideas mailing list