Elegant ways to return multiple values from a function Elegant ways to return multiple values from a function python python

Elegant ways to return multiple values from a function


Pretty much all ML-influenced functional langues (which is most of them) also have great tuple support that makes this sort of thing trivial.

For C++ I like boost::tuple plus boost::tie (or std::tr1 if you have it)

typedef boost::tuple<double,double,double> XYZ;XYZ foo();double x,y,z;boost::tie(x,y,z) = foo();

or a less contrived example

MyMultimap::iterator lower,upper;boost::tie(lower,upper) = some_map.equal_range(key);


A few languages, notably Lisp and JavaScript, have a feature called destructuring assignment or destructuring bind. This is essentially tuple unpacking on steroids: rather than being limited to sequences like tuples, lists, or generators, you can unpack more complex object structures in an assignment statement. For more details, see here for the Lisp version or here for the (rather more readable) JavaScript version.

Other than that, I don't know of many language features for dealing with multiple return values generally. However, there are a few specific uses of multiple return values that can often be replaced by other language features. For example, if one of the values is an error code, it might be better replaced with an exception.

While creating new classes to hold multiple return values feels like clutter, the fact that you're returning those values together is often a sign that your code will be better overall once the class is created. In particular, other functions that deal with the same data can then move to the new class, which may make your code easier to follow. This isn't universally true, but it's worth considering. (Cpeterso's answer about data clumps expresses this in more detail).


PHP example:

function my_funct() {    $x = "hello";    $y = "world";    return array($x, $y);}

Then, when run:

list($x, $y) = my_funct();echo $x.' '.$y; // "hello world"