[Python-ideas] A subclassing API for named tuples?

Raymond Hettinger raymond.hettinger at gmail.com
Mon Feb 18 10:46:36 CET 2013


On Feb 14, 2013, at 5:19 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:

> So, what do people think? Too much magic? Or just the right amount to
> allow a cleaner syntax for named tuple definitions, without
> inadvertently encouraging people to do bad things to their memory
> usage? (Note: for backwards compatibility reasons, we couldn't use a
> custom metaclass for the classes returned by the existing collections
> namedtuple API. However, we could certainly provide a distinct
> collections.NamedTuple type which used a custom metaclass to behave
> this way).

To me, this smells of over-engineering.   For most uses, the current
form of named tuple is simple and clean:

    CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"])

The current form of namedtuple is also very flexible.  The docs for it show
how it can easily be subclassed to add computed fields, new reprs, etc.
It also works great for implementing prototype instance, enums, etc.
And it has a verbose option that makes it self-documenting.

The namedtuple API was born out of mixing the best parts of many different
implementations found in the field.  It went through extensive evaluation,
review and refinement as a recipe on ASPN.   IMO, there is zero need 
to wreck its simplicity by throwing metaclass firepower into the mix.

We really don't need a second way to do it.
For people who care about the memory used
by subclasses, it takes less effort to learn how
to use slots that it does to learn and remember 
an second API for namedtuples.  

After all, the sole justification for __slots__ is to prevent the creation of 
an instance dictionary.   That is what it's for.    I think your real issue 
doesn't have anything to do with named tuples in particular.  
Instead, your issue is with subclassing *any* class that  uses __slots__.



Raymond

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130218/c7067fa3/attachment.html>


More information about the Python-ideas mailing list