[Python-ideas] namedtuple baseclass

Terry Reedy tjreedy at udel.edu
Sun Jan 12 22:17:20 CET 2014


On 1/12/2014 3:01 PM, Raymond Hettinger wrote:
>
> On Jan 11, 2014, at 11:04 PM, Yury Selivanov
> <yselivanov.ml at gmail.com
> <mailto:yselivanov.ml at gmail.com>> wrote:
>
>> I propose to add a baseclass for all namedtuples. Right now 'namedtuple'
>> function dynamically creates a class derived from 'tuple', which
>> complicates
>> things like dynamic dispatch.
>
> A named tuple is a protocol, not a class.
> Here's the glossary entry:
> '''
> named tuple
>
>     Any tuple-like class whose indexable elements are also accessible
>     using named attributes (for example, time.localtime()
>     <library/time.html#time.localtime> returns a tuple-like object where
>     the /year/ is accessible either with an index such as t[0] or with a
>     named attribute like t.tm_year).
>
>     A named tuple can be a built-in type such as time.struct_time
>     <library/time.html#time.struct_time>, or it can be created with a
>     regular class definition. A full featured named tuple can also be
>     created with the factory function collections.namedtuple()
>     <library/collections.html#collections.namedtuple>. The latter
>     approach automatically provides extra features such as a
>     self-documenting representation like Employee(name='jones',
>     title='programmer').
> '''

That is a really nice glossary entry. I had not seen it before.

>> Basically, the only way of checking if an object
>> is an instance of 'namedtuple' is to do "isinstance(o, tuple) and
>> hasattr(o, '_fields')".
>
> Yes, that is the correct way of doing it.

That looks fine to me also, so I agree that nothing new is needed.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list