stylistic question -- optional return value

Michael Tiller mtiller at ford.com
Wed Aug 28 21:33:03 CEST 2002

```Well,

If I understand your problem, I have seen some analogs in numerical
computations where it is beneficial to do what you describe (e.g. reuse
common subexpressions to compute a related value).  Because of this,
languages like MATLAB and Modelica (I believe you know Dag Brueck?) have
tried to make allowances for such situations.

I only learned Python last week so take all this with a big grain of salt,
but doesn't this essentially do what you want:

>>> def evalF(t, der):
ret = {};
ret["x"] = 2*t**2+(t-5)
if der: ret["dxdt"] = 4*t+1
return ret

>>> evalF(2,1)
{'dxdt': 9, 'x': 5}
>>> evalF(2,0)
{'x': 5}

Then you could just pick the answer you want out by name?!?  Does this fall
within your constraints?  Again, remember I'm very new to Python so if I
missed something obvious, my apologies.  It seems like you could do a
similar thing with lists (1-lists seem to be less confusing than 1-tuples).
Or, are you trying to avoid the mutable collection types altogether?

--
Michael Tiller
Ford Motor Company

"Andrew Koenig" <ark at research.att.com> wrote in message
news:yu99znv6c0zx.fsf at europa.research.att.com...
> Suppose I have a function that sometimes returns one value and sometimes
> returns two.  What's the cleanest way to define such an interface?
>
> For the sake of this discussion, I'll use x to refer to the value that
> is always returned and y to refer to the optional value.
>
> If I know that x is always a scalar, one possibility is to return
> either x or (x, y).  However, that strategy rules out the possibility
> of making x a tuple in a future version of this function.  Moreover,
> it makes extracting x more complicated than it needs to be.
>
> Another possibility is to return either (x, None) or (x, y).  Now
> it is easy to extract x from the compound result.  However,
> that strategy removes None from the set of permissible values for y.
>
> Yet another possibility is to return (False, x) or (True, x, y).
> Now x is in a common position, so retrieving it is straightforward.
> However, I can obtain the same information content by returning
> (x,) or (x, y).  However, I can easily imagine people becoming
> confused by 1-tuples.
>
> What is the most Pythonic way of solving this problem?

```