Best way to return multiple values from a function? [closed]
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.y1 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 valueemployee = 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)
.
A lot of the answers suggest you need to return a collection of some sort, like a dictionary or a list. You could leave off the extra syntax and just write out the return values, comma-separated. Note: this technically returns a tuple.
def f(): return True, Falsex, y = f()print(x)print(y)
gives:
TrueFalse