Are multiple return values really harmful? (Re: determining the number of output arguments)

Jeremy Bowers jerf at jerf.org
Thu Nov 18 05:51:00 EST 2004


On Wed, 17 Nov 2004 22:58:56 +0000, Bengt Richter wrote:

> On Wed, 17 Nov 2004 16:49:03 +1300, Greg Ewing <greg at cosc.canterbury.ac.nz> wrote:
> 
>>Jeremy Bowers wrote:
>>> Generally, returning a tuple is either a sign that your return value
>>> should be wrapped up in a class, or the function is doing too much.
>>
> ISTM that a tuple _is_ a class that wraps content for return as a _single value_,
> just like a custom container class instance. What's the problem? The fact that you
> can write

Generally, generally, generally, I say again, generally.

You take every example mentioned to date, which is largely:

* OS code trying to be as thin as possible (stat, socket)
* math-type code where the tuple really is the class, as you suggest
* more-or-less contrived one- or two-liner code

and you've still got way, way, way less than 1% of the code of the vast
majority of programs. 

Like any other code smell, there are times to use it. But I say it's a
*smell*, and those of you implicitly reading that to mean "Returning
tuples is *never* a good idea" are doing me a disservice; please go look
up "code smell" and the word "generally". 

If you use it every once in a while where it is the right solution, great.
I do too. If you're using it every other function in a module, and it
isn't a thin wrapper around some other library, you've got a code smell.
(It's probably a class or two trying to get out.) You've got a *big* code
smell if you are unpacking those return values many times, because now
you've hard coded the size of the tuple into the code in many places. 

Named tuples eliminate the latter, and make the former weaker. But I
wouldn't add named tuples because of this use case, I'd add them because
we could use immutable dictionaries, and this just happens to come along
for the ride (as long as you aren't required to fully consume the tuple on
the left side, otherwise the smell remains).





More information about the Python-list mailing list