stylistic question -- optional return value

Hans Nowak wurmy at
Wed Aug 28 20:32:09 CEST 2002

Andrew Koenig wrote:

> Suppose I have a function that sometimes returns one value and sometimes
> returns two.  What's the cleanest way to define such an interface?

In general, it may be better to use two separate functions, aside... the 
"sometimes it returns A and something it returns B" is usually not a good idea. 
However, I don't know the exact situation.

> 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?

I can think of some yucky solutions, like writing a special class that has one 
or two attributes depending on what you return. That can hardly be called 
"Pythonic", though. :-/

A bit better would be, using a special instance to signify an "empty slot", 
like you use None in your example above:

   class Null: pass
   Null = Null()

Functions can now return (x, y) or (x, Null). The latter cannot be confused 
with (x, y) where y is None.

Still, I believe that rewriting the function (or splitting it up) might be a 
better idea. <0.3 wink>


Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter::

More information about the Python-list mailing list