For returning complex values from a method you have a few popular choices:

Return a tuple with positional values. Those are very easy to unpack in Python and quite attractive because of that. Return a dictionary with the values. This can lead to slightly verbose accessing of the individual values. Return an object of some class you define. This required the definition of a class which can be too verbose for just a simple return value.

Since Python 2.6 you have one additional tool: collections.namedtuple. They give you a very lightweight class but it’s a one-liner to define them.

from collections import namedtuple Child = namedtuple('Child', 'id, user, type, count') def get_first_child(): return Child('id', 'userid', 'special', 10) res = get_first_child() print res print res.id, res.user, res.type, res.count

To create a class you call the namedtuple function with the type name and a string of field names. The field names are separated by whitespace and/or coma. Alternatively you can also pass in a list of strings.

The returned class can be used like any other class – but all values are read-only.

As always, the full details are available in the official API documentation for collections.namedtuple.

This post is part of the Python on the toilet series.