[Tutor] Multiple returns in a function

Kent Johnson kent37 at tds.net
Thu Dec 16 12:09:12 CET 2004


Brian van den Broek wrote:
> Kent Johnson said unto the world upon 2004-12-15 20:16:
>  > I would write
>  > def is_leap_year(year):
>  >     try:
>  >         datetime.date(year, 2, 29)
>  >         return True
>  >     except ValueError:
>  >         return False
> 
> Not an adherent of the "only one exit point" doctrine then, hey? I spent 
> a while a few weeks ago with a bug in a function that happened because 
> I'd not noticed that I had two return statements, so I'm leery of this 
> at the moment. (I concede if the function was long enough to hide that 
> from me, it was probably too long.) I also like the conceptual purity of 
> one way in and one way out. But, in my code above, that is indeed 
> purchased at the cost of the ugly and a bit anomalous assignment of True.

Right you are. I wondered if anyone would notice :-)

I find multiple returns very handy. They can often reduce the indentation of a block or eliminate 
the need for flag variables. And I don't see any benefit from having a single return.

One simple use of multiple returns is to handle different conditions in a function. Especially for 
error conditions. I like to handle special cases early in a function. (This is the GuardClause idiom 
from the web page you cited: http://c2.com/cgi/wiki?GuardClause) For example something like

def fn(a, b):
   if not a:
     return None

   if b == 0:
     return 0

   # Calculate result from a and b
   return result

Without the multiple returns this might look like

def fn(a, b):
   if not a:
     result = None

   elif b == 0:
     result = 0

   else:
     # Calculate result

   return result

To me the first version is cleaner and clearer. The exceptional cases are handled unambiguously at 
the start of the fn, the rest of the code just handles the normal case.

Kent


More information about the Tutor mailing list