return - Alternatives for returning multiple values from a Python function - Stack Overflow
How do you return multiple variables in a function?
language comparison - What are the different ways of handling multiple return values? - Programming Language Design and Implementation Stack Exchange
How to call a Python function that returns multiple values with Python Interface
Videos
Hello developers, I want to know about how can I return multiple values from a function. I have read few articles but still confused.
Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example.
>>> import collections
>>> Point = collections.namedtuple('Point', ['x', 'y'])
>>> p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2
In recent versions of Python 3 (3.6+, I think), the new typing library got the NamedTuple class to make named tuples easier to create and more powerful. Inheriting from typing.NamedTuple lets you use docstrings, default values, and type annotations.
Example (From the docs):
class Employee(NamedTuple): # inherit from typing.NamedTuple
name: str
id: int = 3 # default value
employee = Employee('Guido')
assert employee.id == 3
For small projects I find it easiest to work with tuples. When that gets too hard to manage (and not before) I start grouping things into logical structures, however I think your suggested use of dictionaries and ReturnValue objects is wrong (or too simplistic).
Returning a dictionary with keys "y0", "y1", "y2", etc. doesn't offer any advantage over tuples. Returning a ReturnValue instance with properties .y0, .y1, .y2, etc. doesn't offer any advantage over tuples either. You need to start naming things if you want to get anywhere, and you can do that using tuples anyway:
def get_image_data(filename):
[snip]
return size, (format, version, compression), (width,height)
size, type, dimensions = get_image_data(x)
IMHO, the only good technique beyond tuples is to return real objects with proper methods and properties, like you get from re.match() or open(file).
Push them onto the stack
This really only applies to stack-based languages, and perhaps Assembly. The good thing about this approach is that its somewhat more natural to work with the returned values. If you do divmod, you can pop once to get the quotient, pop the next element to get the remainder. The downside is that if you want to call a function that returns multiple values and immediately pass them on, it might be a bit cumbersome, depending on the language.
Custom types
In languages such as Java and Kotlin, which really love their nominal typing, you would make a new class specific to that one function. For example, divmod might return a DivmodResult object with fields quotient and remainder (Kotlin does have a Pair class in its standard library, but it's dropped actual tuples now).
Advantages:
- When you have to return 4 or more values, it really helps to have a class specifically for that purpose if you have a statically typed language. I'd rather see a return type of
FooResultthan some enormous tuple like(int, String, BarProducer, String, int)
Disadvantages:
- Making a whole class for a single function is annoying. Some languages do have syntactic sugar for this (e.g.
data classin Kotlin) but it's so much easier to use something like tuples or lists instead. In Java, you'll have to make getters and setters and constructors for a minor class that might only be used in one or two places.
I think the choices need to be considered strictly from the caller's point of view: what is the consumer most likely to need to do?
And what are the salient features of each collection?
- The tuple is accessed in order and immutable
- The list is accessed in order and mutable
- The dict is accessed by key
The list and tuple are equivalent for access, but the list is mutable. Well, that doesn't matter to me the caller if I'm going to immediately unpack the results:
score, top_player = play_round(players)
# or
idx, record = find_longest(records)
There's no reason here for me to care if it's a list or a tuple, and the tuple is simpler on both sides.
On the other hand, if the returned collection is going to be kept whole and used as a collection:
points = calculate_vertices(shape)
points.append(another_point)
# Make a new shape
then it might make sense for the return to be mutable. Homogeneity is also an important factor here. Say you've written a function to search a sequence for repeated patterns. The information I get back is the index in the sequence of the first instance of the pattern, the number of repeats, and the pattern itself. Those aren't the same kinds of thing. Even though I might keep the pieces together, there's no reason that I would want to mutate the collection. This is not a list.
Now for the dictionary.
the last one creates more readable code because you have named outputs
Yes, having keys for the fields makes heterogenous data more explicit, but it also comes with some encumbrance. Again, for the case of "I'm just going to unpack the stuff", this
round_results = play_round(players)
score, top_player = round_results["score"], round_results["top_player"]
(even if you avoid literal strings for the keys), is unnecessary busywork compared to the tuple version.
The question here is threefold: how complex is the collection, how long is the collection going to be kept together, and are we going to need to use this same kind of collection in a bunch of different places?
I'd suggest that a keyed-access return value starts making more sense than a tuple when there are more than about three members, and especially where there is nesting:
shape["transform"]["raw_matrix"][0, 1]
# vs.
shape[2][4][0, 1]
That leads into the next question: is the collection going to leave this scope intact, somewhere away from the call that created it? Keyed access over there will absolutely help understandability.
The third question -- reuse -- points to a simple custom datatype as a fourth option that you didn't present.
Is the structure solely owned by this one function? Or are you creating the same dictionary layout in many places? Do many other parts of the program need to operate on this structure? A repeated dictionary layout should be factored out to a class. The bonus there is that you can attach behavior: maybe some of the functions operating on the data get encapsulated as methods.
A fifth good, lightweight, option is namedtuple(). This is in essence the immutable form of the dictionary return value.
Don't think about functions returning multiple arguments. Conceptually, it is best to think of functions as both receiving and returning a single argument. A function that appears to accept multiple arguments actually receives just a single argument of tuple (formally product) type. Similarly, a function that returns multiple arguments is simply returning a tuple.
In Python:
def func(a, b, c):
return b, c
could be rewritten as
def func(my_triple):
return (my_triple[1], my_triple[2])
to make the comparison obvious.
The first case is merely syntactic sugar for the latter; both receive a triple as an argument, but the first pattern-matches on its argument to perform automatic destructuring into its constituent components. Thus, even languages without full-on general pattern-matching admit some form of basic pattern matching on some of their types (Python admits pattern-matching on both product and record types).
To return to the question at hand: there is no single answer to your question, because it would be like asking "what should be the return type of an arbitrary function"? It depends on the function and the use case. And, incidentally, if the "multiple return values" are really independent, then they should probably be computed by separate functions.