A tuple in order to pass returned values ?

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Oct 7 05:43:30 EDT 2011


Steven D'Aprano wrote:
> 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)
>
>   
I don't have access to namedtuple, working with python 2.5
It sounds to me that namedtuple exactly tries to fix what I dislike in 
tuples : undocumented packing of unrelated data.

However, I'm not sure it fixes the main issue: unpacking. Unpacking 
prevents you from adding any additional fields to your 'tuple' without 
breaking any line of code that was unpacking the tuple (to oppose to 
accessing an object attribute). And it did annoy me a lot when improving 
applications. Now I'm using tuples only in small applications, and try 
to avoid unpacking as much as possible.

namedtuple sounds great (if you don't use unpacking :o) ), too bad it is 
available only from python 2.6.

JM





More information about the Python-list mailing list