Coding style and else statements

Tal Einat tal.no.no.spam at gmail.com
Mon Aug 28 18:54:02 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.
>
> Comments?

I usually prefer the second option because it is more scalable - it is
possible to later add code to the function to return other values
elsewhere in its code, and still have -1 returned by default, without
changing the original code.

As for structure, in the second example there is a clear point at which
the function return a value, unless some other value is return
elsewhere. In the first one you have to comprehend the entire if-else
statement to understand that a value will always be returned at this
point.

Another worthy alternative mentioned is:

def foo(thing):
   if thing:
     result = thing + 1
   else:
     result = -1
   return result

This is scalable as described above, and also has only one exit point,
which makes it a much simpler function. However, it forces someone
reading the code to backtrack from the return statement and search for
places where "result" could be set.

I usually start with your second example, and if I need more control
over the returned value I change the code to use this last method.
("More control" could be many things - checking the value for
debugging, applying some transformation on the returned value before
returning it...)

- Tal




More information about the Python-list mailing list