[Python-ideas] for/else statements considered harmful

Guido van Rossum guido at python.org
Fri Jun 8 19:37:17 CEST 2012

On Fri, Jun 8, 2012 at 8:08 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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?

> Not in my opinion. Due to laziness (why write an extra line that isn't
> necessary?), I tend to prefer the first version, but have been known to also
> use the second version on some occasions.

It's indeed a very subtle choice, and for simple examples it usually
doesn't much matter.

I tend to like #1 better if "then" block is small (especially an error
exit or some other "early return" like a cache hit) and the "else"
block is more substantial -- it saves an indentation level. (I also
sometimes reverse the sense of the test just to get the smaller block
first, for this reason.)

When there are a bunch of elif clauses each ending with return (e.g.
emulating a switch) I think it makes more sense to use "else" for the
final clause, for symmetry.

So maybe my gut rule is that if the clauses are roughly symmetrical,
use the else, but if there is significant asymmetry, don't bother.

--Guido van Rossum (python.org/~guido)

More information about the Python-ideas mailing list