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

Dave Brueck dave at pythonapocrypha.com
Wed Nov 17 11:21:33 EST 2004


Greg Ewing 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.
> 
> 
> While I suspect you may be largely right, I
> find myself wondering why this should be so. 

*Is* it largely right? I don't think so. As you said, there doesn't seem to be 
anything "wrong" with passing multiple pieces of data _into_ a function, so why 
should we assume that complex data passing should be so one way?

One of my biggest pet peeves about programming in C, for example, is that you 
are often forced to wrap stuff up into a structure just to pass data back and 
forth - you create the structure, populate it, send it, and then pull out the data.

In many, many cases this is nothing more than poor-man's tuple unpacking, and 
you end up with lots of extra work and lots of one-off structures. Also annoying 
is the use of "out" parameters, which is again basically manual tuple unpacking.

Python isn't too different from C wrt deciding when to move from "bare" 
parameters to a structure or object - is the number of parameters becoming 
cumbersome? are the interrelationships becoming complex? will I need to use 
those same parameters as a group elsewhere? etc. The difference is that Python 
facilitates more natural data passing on the return.

A function like divmod is a prime example; rather than having

div = 0
mod = 0
divmod(x,y, &div, &mod)

we instead have the much more elegant

div, mod = divmod(x,y)

We can definitely come up with some hints or guidelines ("if your function 
returns 10 parameters, that's probably bad" or "if the parameters are tightly 
coupled and/or are often used & passed along together to different functions, 
you probably should wrap them into an object"), but I don't think returning 
tuples is _generally_ a sign of anything good or bad.

-Dave



More information about the Python-list mailing list