Coding style and else statements

Carl Banks pavlovevidence at gmail.com
Tue Aug 29 20:38:30 EDT 2006


tobiah wrote:
> def foo(thing):
> 	if thing:
> 		return thing + 1
> 	else:
> 		return -1
>
> def foo(thing):
> 	if thing:
> 		return thing + 1
> 	return -1
>
> Obviously both do the same thing.  The first is
> possibly clearer, while the second is more concise.


I almost always go with #2.  The else clause is redundant and
potentially misleading in the first one.  (A casual programmer might
not notice that it always returns and so add code beneath it, or a
casual code checker might not notice that the end is unreachable, and
flag the function as both returning a value and returning the default.)

However, I have rare cases where I do choose to use the else (ususally
in the midst of a complicated piece of logic, where it's be more
distracting than concise).  In that case, I'd do something like this:

def foo(thing):
    if thing:
        return thing+1
    else:
        return -1
    assert False


Carl Banks




More information about the Python-list mailing list