Best Way to Return Multiple Values from a Function

Return multiple values from function

Dart doesn't support multiple return values.

You can return an array,

List foo() {
return [42, "foobar"];
}

or if you want the values be typed use a Tuple class like the package https://pub.dartlang.org/packages/tuple provides.

See also either for a way to return a value or an error.

How can I return two values from a function in Python?

You cannot return two values, but you can return a tuple or a list and unpack it after the call:

def select_choice():
...
return i, card # or [i, card]

my_i, my_card = select_choice()

On line return i, card i, card means creating a tuple. You can also use parenthesis like return (i, card), but tuples are created by comma, so parens are not mandatory. But you can use parens to make your code more readable or to split the tuple over multiple lines. The same applies to line my_i, my_card = select_choice().

If you want to return more than two values, consider using a named tuple. It will allow the caller of the function to access fields of the returned value by name, which is more readable. You can still access items of the tuple by index. For example in Schema.loads method Marshmallow framework returns a UnmarshalResult which is a namedtuple. So you can do:

data, errors = MySchema.loads(request.json())
if errors:
...

or

result = MySchema.loads(request.json())
if result.errors:
...
else:
# use `result.data`

In other cases you may return a dict from your function:

def select_choice():
...
return {'i': i, 'card': card, 'other_field': other_field, ...}

But you might want consider to return an instance of a utility class (or a Pydantic/dataclass model instance), which wraps your data:

class ChoiceData():
def __init__(self, i, card, other_field, ...):
# you can put here some validation logic
self.i = i
self.card = card
self.other_field = other_field
...

def select_choice():
...
return ChoiceData(i, card, other_field, ...)

choice_data = select_choice()
print(choice_data.i, choice_data.card)

Returning multiple values from a C++ function

For returning two values I use a std::pair (usually typedef'd). You should look at boost::tuple (in C++11 and newer, there's std::tuple) for more than two return results.

With introduction of structured binding in C++ 17, returning std::tuple should probably become accepted standard.

Best practice for returning multiple values in Java?

No, this kind of structure doesn't exists nativily in Java, but you can look at JavaTuples library that may suit your need and provide a quite elegant solution. Using a Triplet<Boolean, String, Boolean>

How to return multiple values ​with a function?

You can return an array from the first function and pass each element to another other function as independent argument using Spread Operator.

var resultado;function num_2(repet){  return [...Array(repet)].map((x,i) => i)}function sumarr(a,b,c){ return a + b + c}console.log("\n" + "callback 2: " + sumarr(...num_2(3)))

Is it pythonic for a function to return multiple values?

Absolutely (for the example you provided).

Tuples are first class citizens in Python

There is a builtin function divmod() that does exactly that.

q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x

There are other examples: zip, enumerate, dict.items.

for i, e in enumerate([1, 3, 3]):
print "index=%d, element=%s" % (i, e)

# reverse keys and values in a dictionary
d = dict((v, k) for k, v in adict.items()) # or
d = dict(zip(adict.values(), adict.keys()))

BTW, parentheses are not necessary most of the time.
Citation from Python Library Reference:

Tuples may be constructed in a number of ways:

  • Using a pair of parentheses to denote the empty tuple: ()
  • Using a trailing comma for a singleton tuple: a, or (a,)
  • Separating items with commas: a, b, c or (a, b, c)
  • Using the tuple() built-in: tuple() or tuple(iterable)

Functions should serve single purpose

Therefore they should return a single object. In your case this object is a tuple. Consider tuple as an ad-hoc compound data structure. There are languages where almost every single function returns multiple values (list in Lisp).

Sometimes it is sufficient to return (x, y) instead of Point(x, y).

Named tuples

With the introduction of named tuples in Python 2.6 it is preferable in many cases to return named tuples instead of plain tuples.

>>> import collections
>>> Point = collections.namedtuple('Point', 'x y')
>>> x, y = Point(0, 1)
>>> p = Point(x, y)
>>> x, y, p
(0, 1, Point(x=0, y=1))
>>> p.x, p.y, p[0], p[1]
(0, 1, 0, 1)
>>> for i in p:
... print(i)
...
0
1


Related Topics



Leave a reply



Submit