Named tuples

Bryan belred1 at yahoo.com
Thu Nov 18 03:57:23 CET 2004


Carlos Ribeiro wrote:
> On Wed, 17 Nov 2004 17:13:45 -0800, Jeff Shannon <jeff at ccvcorp.com> wrote:
> 
>>Carlos Ribeiro wrote:
>>
>>
>>>4. Named attribute access is supported by __getattr__. Names are
>>>looked up on the magic __names__ attribute of the tuple.
>>>
>>>5. On slicing, a named tuple should return another named tuple. This
>>>means that the __names__ tuple has to be sliced also.
>>>
>>>
>>
>>Hm.  If __names__ is a tuple, then does that tuple have a __names__
>>attribute as well?
>>
>>(In practice, I can't imagine any reason why tuple.__names__.__names__
>>should ever be anything other than None, but the potential recursiveness
>>makes me nervous...)
> 
> 
> Humm. The worst case is if it's done in a circular fashion, as in:
> 
> mytuple.__names__ = nametuple
> nametuple.__names__ = mytuple
> 
> That's weird. The best that I can imagine now is that it would be
> illegal to assign a named tuple to the __names__ member of another
> tuple.
> 


it should be possible to avoid a recusive problem:

 >>> a = ('1', '2')
 >>> a.__names__ = ('ONE', 'TWO')
 >>> a[0]
'1'
 >>> a.ONE
'1'
 >>> a[0] is a.ONE
True
 >>> b = (3, 4)
 >>> b.__names__ = a
 >>> b[0]
3
 >>> b.1
3
 >>> b.ONE
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
IndexError: tuple index out of range



 >>> a = (1, 2)
 >>> a.__names__ = ('ONE', 'TWO')
 >>> a[0]
1
 >>> a.ONE
1
 >>> a[0] is a.ONE
True
 >>> b = (3, 4)
 >>> b.__names__ = a
 >>> b[0]
3
 >>> b.1
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
TypeError: tuple must contain strings



or maybe __names__ could be a property method and do some validation on assignment.


 >>> a = (1, 2)
 >>> a.__names__ = ('ONE', 'TWO')
 >>> a[0]
1
 >>> a.ONE
1
 >>> a[0] is a.ONE
True
 >>> b = (3, 4)
 >>> b.__names__ = a
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
TypeError: tuple must contain strings



bryan



More information about the Python-list mailing list