[Python-ideas] Classes inside functions [was Re: Add __parent__ to all classes, functions, and modules]

Nick Coghlan ncoghlan at gmail.com
Tue Oct 7 13:02:21 CEST 2014


On 7 October 2014 13:54, Steven D'Aprano <steve at pearwood.info> wrote:
> On Mon, Oct 06, 2014 at 10:23:42AM -0700, Guido van Rossum wrote:
>
>> How namedtuple is implemented should be nobody's business, except
>> Raymond's, and it certainly isn't a pattern to be recommended. That's why
>> it's in the stdlib -- so you don't have to write such code yourself. Same
>> for enums. Yes, it *can* be done. But it takes superhuman skills to get it
>> right and it still won't be maintainable (TBH, every time I see the
>> namedtuple implementation I have to resist the urge to rewrite it. :-)
>
> Heh :-)
>
> I was curious to see how much code in namedtuple actually needed to be
> run through exec, so I forked Raymond's recipe on ActiveState, and
> re-wrote with the Inner class as a regular nested class, and only a
> two-line __new__ method needing to be run through exec.
>
> http://code.activestate.com/recipes/578918-yet-another-namedtuple/
>
> It passes the minimal tests in the recipe. I haven't taken it any
> further.

One nice thing about the current impl is you can actually dump the
full source code of the underlying class implementation. That ties in
to another nice property, which is that anyone that understands class
definitions and exec could maintain most of the current
implementation. It would be tough to write it from scratch (since
there are some subtle details to get right), but it's still a much
lower knowledge barrier to get over than is the case with the
corresponding dynamic type creation code.

By contrast, writing it out directly means reimplementing several
things the interpreter will otherwise take care of, which also means
you may not automatically benefit from changes to the way class
definitions work. For example, that recipe version doesn't appear to
adjust __qualname__ at all, while namedtuple (without any changes to
the namedtuple implementation) automatically sets it to match
__name__.

Maintainability is a complicated thing, and our instincts don't always
get the trade-offs right :)

Cheers,
Nick.

P.S. Despite everything I said above, in most cases, dynamic type
creation is still going to be a better idea. namedtuple itself just
isn't one of those cases.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list