A tuple in order to pass returned values ?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Oct 6 22:02:26 EDT 2011
Jean-Michel Pichavant wrote:
> In a general manner, ppl will tend to use the minimum arguments
> required. However, do not pack values into tuple if they are not related.
How would you return multiple values if not in a tuple?
Tuples are *the* mechanism for returning multiple values in Python. If
you're doing something else, you're wasting your time.
> A better thing to do would be to use objects instead of tuples, tuples
> can serve as lazy structures for small application/script, they can
> become harmful in more complexe applications, especialy when used in
> public interfaces.
First off, tuples *are* objects, like everything else in Python.
If you are creating custom classes *just* to hold state, instead of using a
tuple, you are wasting time. Instead of this:
class Record:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
result = Record(1, 2, 3)
Just use a tuple or a namedtuple: the work is already done for you, you have
a well-written, fast, rich data structure ready to use. For two or three
items, or for short-lived results that only get used once, an ordinary
tuple is fine, but otherwise a namedtuple is much better:
from collections import namedtuple
result = namedtuple('Record', 'x y z')(1, 2, 3)
--
Steven
More information about the Python-list
mailing list