Too many return-statements = bad style?
Andrew Koenig
ark at acm.org
Fri Jul 9 15:40:33 EDT 2004
"george young" <gry at ll.mit.edu> wrote in message
news:20040709141411.0bd5f523.gry at ll.mit.edu...
> > Here is the same logic in a form that I find much easier to follow:
> >
> > def getFoo (i):
> > if not blah: return 3
> > if i == 4: return 1
> > return 2
>
> Hmm... contrariwise, I find:
>
> def getFoo(i):
> if not blah: return 3
> elif i == 4: return 1
> else: return 2
>
> more compelling, the if--elif--else emphasizing that these are three
> possible outcomes; the last return is in the same logical level as
> the other returns, so it seems right that it be in a similar syntactic
> position.
If I were going to bother to write the redundant "else"s, I would also be
inclined to give the code a single exit point:
def getFoo(i):
if not blah:
result = 3
elif i == 4:
result = 1
else:
result = 2
return result
That way, if I want to come back later and print the result before returning
(for debugging purposes), I can do so by inserting a single line of code.
Of course, this whole argument is pretty silly without a more plausible
context :-)
More information about the Python-list
mailing list