Named tuples

Carlos Ribeiro carribeiro at gmail.com
Thu Nov 18 08:58:09 EST 2004


On 18 Nov 2004 12:58:49 GMT, Duncan Booth <duncan.booth at invalid.invalid> wrote:
> Carlos Ribeiro wrote:
> 
> 
> 
> > There are a few requirements that can be imposed to avoid problems.
> > First, __names__ is clearly a property, acessed via get & set (which
> > allows to trap some errors). It should accept only tuples as an
> > argument (not lists) to avoid potential problems with external
> > references and mutability of the names. As for the validation, I'm not
> > sure if it's a good idea to check for strings. maybe just check if the
> > 'names' stored in the tuple are immutable (or perhaps 'hashable') is
> > enough.
> >
> 
> Your idea of a __names__ attribute suffers from a problem that the common
> use case would be to return a tuple with appropriate names. Right now you
> can do that easily in one statement but if you have to assign to an
> attribute it becomes messy.
> 
> 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.

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list