[Python-Dev] Possible rough edges in Python 3 metaclasses (was Re: Language reference updated for metaclasses)

Nick Coghlan ncoghlan at gmail.com
Tue Jun 5 15:17:54 CEST 2012


On Tue, Jun 5, 2012 at 10:37 PM, Xavier Morel <catch-all at masklinn.net> wrote:
> On 5 juin 2012, at 14:24, Nick Coghlan <ncoghlan at gmail.com> wrote:
>>> Metaclasses *do* have a problem with composition and lexical
>>> decorators don't play nicely with inheritance, but a dynamic decorator
>>> system modelled to some degree on the old __metaclass__ mechanics
>>> could fill the gap nicely.
>>
>> PEP written and posted: http://www.python.org/dev/peps/pep-0422/
>> More toy examples here:
>> https://bitbucket.org/ncoghlan/misc/src/default/pep422.py
>>
>
> Does it really make sense to meld decorators and inheritance so? With this, class "decorators" become way more than mere decorators and start straying quite far away from their function-based counterparts (which are not "inherited" when overriding methods but are statically applied instead)

Lexical class decorators won't go away, and will still only apply to
the associated class definition.

There are a couple of key points about class decorators that make them
a *lot* easier to reason about than metaclasses:

1. They have a very simple expected API: "class in, class out"
2. As a result of 1, they can typically be pipelined easily: in the
absence of decorator abuse, you can take the output of one class
decorator and feed it to the input of the next one

Metaclasses live at a different level of complexity all together - in
order to make use of them, you need to have some understanding of how
a name, a sequence of bases and a namespace can be combined to create
a class object. Further, because it's a transformative API (name,
bases, ns -> class object), combining them requires a lot more care
(generally involving inheriting from type and making appropriate use
of super() calls).

However, even when all you really want is to decorate the class after
it has been created, defining a metaclass is currently still necessary
if you also want to be notified when new subclasses are defined. This
PEP proposes that those two characteristics be split: if all you want
is inheritance of decorators, then dynamic decorators are a much
simpler, more multiple inheritance friendly solution than using a
custom metaclass, leave full metaclass definitions for cases where you
really *do* want almost complete control over the class creation
process.

That said, actively discouraging PJE from his current scheme that
involves monkeypatching __build_class__ and publishing "Python 3 (with
monkeypatched undocumented builtins) compatible" packages on PyPI is
definitely a key motivation in putting this proposal together.

Cheers,
Nick.

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


More information about the Python-Dev mailing list