Named tuples

Bengt Richter bokr at oz.net
Thu Nov 18 05:06:08 CET 2004


On Wed, 17 Nov 2004 23:23:02 -0200, Carlos Ribeiro <carribeiro at gmail.com> 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.
>
>-- 
>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

Just to introduce a different perspective, a viewer for unnamed sequences,
rather than a new type with names:

 >>> class SeqVu(object):
 ...     """create sequence viewer object"""
 ...     def __init__(self, names=''):
 ...         for i, name in enumerate(names.split()):
 ...             setattr(self, name, i)
 ...     def __call__(self, tup):
 ...         """accept tup and return self for named access"""
 ...         self.tup = tup; return self
 ...     def __setitem__(self, i, tup):
 ...         """provide assignment target for tuples to view"""
 ...         self.tup = tup
 ...     def __getattribute__(self, name):
 ...         """get tuple item by name"""
 ...         return object.__getattribute__(self,'tup')[
 ...             object.__getattribute__(self, name)]
 ...
 >>> by3names = SeqVu('zero one two')
 >>> t = range(5)
 >>> by3names(t).one
 1
 >>> by3names(t).two
 2
 >>> for by3names[:] in [(i, chr(i)) for i in xrange(65, 70)]:
 ...     print by3names.one, by3names.zero
 ...
 A 65
 B 66
 C 67
 D 68
 E 69

Think of this as compost for the thought garden, not a bouquet ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list