Named tuples

Bryan belred1 at yahoo.com
Thu Nov 18 09:21:58 EST 2004


Carlos Ribeiro wrote:
> 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.
> 

but doesn't this feel more pythonic and more consistant?

return ('ONE':'1', 'TWO':'2')




More information about the Python-list mailing list