[Python-ideas] namedtuple literals [Was: RE a new namedtuple]

Nathaniel Smith njs at pobox.com
Thu Jul 20 02:58:14 EDT 2017

On Wed, Jul 19, 2017 at 9:06 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> A question worth asking will be whether or not
> "collections.namedtuple" will implicitly participate in the use of the
> type cache, and I think the answer needs to be "No". The problem is
> twofold:
> 1. collections.namedtuple accepts an additional piece of info that
> won't be applicable for ntuple types: the *name*
> 2. collections.namedtuple has existed for years *without* implicit
> type caching, so adding it now would be a bit weird
> That means the idiomatic way of getting the type of an ntuple would be
> to create an instance and take the type of it:    type((x=1, y=2))
> The could still be the same kind of type as is created by
> collections.namedtuple, or else a slight variant that tailors repr()
> and pickling support based on the fact it's a kind of tuple literal.

The problem with namedtuple's semantics are that they're perfect for
its original use case (replacing legacy tuple returns without breaking
backwards compatibility), but turn out to be sub-optimal for pretty
much anything else, which is one of the motivations behind stuff like
attrs and Eric's dataclasses PEP:

>From the above it sounds like this ntuple literal idea would be giving
us a third independent way to solve this niche use case (ntuple,
namedtuple, structseq). This seems like two too many? Especially given
that namedtuple is already arguably *too* convenient, in the sense
that it's become an attractive nuisance that gets used in places where
it isn't really appropriate.

Also, what's the advantage of (x=1, y=2) over ntuple(x=1, y=2)? I.e.,
why does this need to be syntax instead of a library?


Nathaniel J. Smith -- https://vorpus.org

More information about the Python-ideas mailing list