[Python-Dev] Submitting PEP 422 (Simple class initialization hook) for pronouncement

Nick Coghlan ncoghlan at gmail.com
Sun Feb 10 15:09:55 CET 2013


On Sun, Feb 10, 2013 at 11:34 PM, Antoine Pitrou <solipsis at pitrou.net> wrote:
> Nobody can claim this is simple and easy to wrap your head around. It
> is a maintenance burden, and it discourages understanding of the
> underlying model by anyone but language experts.

You think anyone but language experts fully understands the metaclass
mechanism now? *I* got the description of some details wrong in the
PEP, and I'm probably in the top half dozen people on the planet when
it comes to understanding how Python 3's class model works.

Plenty of people understand decorators though, and that's all
__init_class__ is: a special class decorator that is applied before
any other decorators, and is automatically inherited by subclasses. It
massively lowers the barrier to entry for inherited post-modification
of classes.

Will it mean people will only bother to understand metaclasses if they
actually *need* metaclass.__prepare__ or to control the identity of
the object returned by metaclass.__call__? Absolutely. However, I
don't see that as any different from the fact that vastly more people
understand how to use instance __init__ methods correctly than
understand the ins and outs of using __new__ to control the *creation*
of the object, rather than merely initialising it after it is already
created. In some respects, cleanly separating out the two steps of
controlling initialisation and controlling creation can actually make
the two easier to grasp (since you can tackle them individually as
distinct concepts, rather than having to wrap your head around both of
them at the same time).

As far as the maintenance burden goes, the patch to enable PEP 422 for
types.new_class() is trivial:

-    return meta(name, bases, ns, **kwds)
+    cls = meta(name, bases, ns, **kwds)
+    try:
+        initcl = cls.__init_class__
+    except AttributeError:
+        pass
+    else:
+        initcl()
+    return cls

The change in the builtin.__build_class__ implementation is similarly
trivial (and has the same semantics), it's just more verbose due to
its being written in C.

The documentation changes are quite straightforward (moving
__init_class__ and decorator invocation out to their own subsection),
and the tests Daniel has provided are extensive.

Cheers,
Nick.

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


More information about the Python-Dev mailing list