stylistic question -- optional return value
Peter Hansen
peter at engcorp.com
Wed Aug 28 18:39:55 EDT 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?
>
[...]
> 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.
Can you imagine them becoming confused by 1-lists? Why not just
return a list, always, with one or more items in it. len() is
available to check which you have if you need it.
> What is the most Pythonic way of solving this problem?
Personally, I'd probably use a list because I eschew tuples most
of the time. In this case, if I thought I wanted a tuple, I would
return a tuple and assume no one would get confused by them.
The only time I imagine someone getting confused by a 1-tuple
is when someone is expected to create one to pass *in* to my
functions, not when my function is returning one.
Maybe I'm wrong about that, but I've never heard of anyone being
confused upon receiving a 1-tuple.
Definitely, in my opinion, all the other suggestions including
sentinels and special classes, are much less Pythonic than a
nice simple list or tuple.
-Peter
More information about the Python-list
mailing list