[Tutor] multiple function returns

Peter Otten __peter__ at web.de
Fri Jun 28 09:48:23 CEST 2013


Jim Mooney wrote:

> What's the Pythonic standard on multiple returns from a function? It
> seems easiest to just return from the point where the function fails
> or succeeds, even it that's multiple points. Or is it considered best
> to defer everything to one return at the end?

Well, if the function *fails* it is usually better to have it raise an 
exception:

>>> def num_to_name(value):
...     if value == 0:
...             return "zero"
...     if value < 0:
...             return "minus " + num_to_name(-value)
...     if value != 42:
...             raise ValueError("Sorry, I cannot convert 
{!r}".format(value))
...     return "forty-two"
... 
>>> num_to_name(0)
'zero'
>>> num_to_name(42)
'forty-two'
>>> num_to_name(-42)
'minus forty-two'
>>> num_to_name(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in num_to_name
ValueError: Sorry, I cannot convert 7
>>> num_to_name(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in num_to_name
TypeError: bad operand type for unary -: 'NoneType'

You get the last exception for free -- for the price that the error message 
is not under your control.



More information about the Tutor mailing list