[Python-Dev] namedtuple implementation grumble

Raymond Hettinger raymond.hettinger at gmail.com
Mon Jun 9 06:05:17 CEST 2014


On Jun 8, 2014, at 6:42 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:

> >> I seem to remember a previous discussion that concluded that duck typing
> >> based on _fields was the way to go.  (It's a public API, despite the _,
> >> due to name-tuple's attribute namespacing issues.)
> >
> >
> > Yes.  That is the recommended approach.
> >
> > IIRC that was Guido's suggestion rather than creating an abstract
> > base class for a named tuple (any tuple-like class with indexable
> > elements that are also accessible using named attributes).
> 
> Given the somewhat periodic recurrence of the question, might it be worth making an ABC after all, with "subclass of tuple with a _fields attribute" as its default check?
> 
> "isinstance(obj, collections.NamedTupleABC)" is quite a bit more self-documenting than "isinstance(obj, tuple) and hasattr(obj, '_fields')"
> 
The "isinstance(obj, tuple)" part isn't a requirement.  The concept of a named tuple is meant to include structseq objects or user defined classes that have are "tuple-like with indexable elements that are also accessible using named attributes" (see the definition in the glossary).

I could add a note to the docs saying that hasattr(obj, '_fields') is the preferred way to check for named tuples produced by the namedtuple() factory function, but it would be a waste to introduce an ABC for this. (Consider the failure of the Callable() abc leading to us deciding to reintroduce the callable() builtin function, and consider the general unwillingness to test for iterability using the Iterable abc).

Another issue is that a straight abc wouldn't be sufficient.  What we would really want is to check for is:
1) the presence of a _fields tuple (an abc can do this)
2) to check that all of the attribute names specified in _fields are defined (ABCMeta doesn't do this)
3) and that the type is a Sequence (ABCMeta can do this).

An tricked-out ABC extension might be worth it if it provided some non-trivial mixin capabilities for implementing homegrown named tuples (not created by the factory function), but I don't think we want to go there.  The problem isn't important enough to warrant throwing this much code and a new API at it (duck-typing the attributes and checking for _fields is a practical solution that works even on older pythons).


Raymond  



 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20140608/3b1c4782/attachment-0001.html>


More information about the Python-Dev mailing list