Named tuples

Duncan Booth duncan.booth at invalid.invalid
Thu Nov 18 12:01:34 EST 2004


Carlos Ribeiro wrote:

>> An alternative would be so add a named argument to the tuple
>> constructor so we can do:
>> 
>>         return tuple(('1', '2'), names=('ONE', 'TWO'))
>> 
>> and that would set the __names__ property. If you allow this then you
>> can make the __names__ property readonly and the problem of
>> introducing a cycle in the __names__ attributes goes away.
> 
> I think that a better way to solve the problem is to create a names
> method on the tuple itself:
> 
> return ('1', '2').names('ONE', 'TWO')
> 
> It's shorter and clean, and avoids a potential argument against named
> parameters for the tuple constructor -- none of the standard
> contructors take named parameters to set extended behavior as far as I
> know.
> 
It doesn't have to be a named parameter, it could just be a second 
positional parameter but I think a named parameter reads better.

The problem with that is that you are still breaking the rule that tuples 
should be immutable. Currently there is no easy way to copy a tuple:

>>> a = (1, 2)
>>> b = tuple(a)
>>> b is a
True
>>> import copy
>>> b = copy.copy(a)
>>> b is a
True

Once I have a tuple I know it isn't going to change no matter what happens. 
You could say that the names method can only be called once, but even then 
the tuple is still changing after its creation and you are still going to 
have to introduce some way for me to take a tuple with one set of names and 
create a new tuple with a different set of names such as changing the 
behaviour of the tuple constructor and the copy.copy function.

Another way to avoid the named argument would be to provide tuple with a 
factory method. How about:

   return tuple.named((1, 2), ('one', 'two))



More information about the Python-list mailing list