[Python-Dev] What is the design purpose of metaclasses vs code generating decorators? (was Re: PEP 557: Data Classes) (original) (raw)

Nick Coghlan ncoghlan at gmail.com
Fri Oct 13 08:53:23 EDT 2017


On 13 October 2017 at 19:35, Martin Teichmann <lkb.teichmann at gmail.com> wrote:

> Metaclasses currently tend to serve two distinct purposes: > > 1. Actually altering the runtime behaviour of a class and its children in > non-standard ways (e.g. enums, ABCs, ORMs) > 2. Boilerplate reduction in class definitions, reducing the amount of code > you need to write as the author of that class > > Nobody has a problem with using metaclasses for the first purpose - that's > what they're for.

I am that nobody. The examples you give would be much nicer solved with decorators. Especially for ABCs it would be much better, because the fact that a class is an ABC is explicitly not inherited - its entire reason of existence is to be inherited with all the abstractness going away. And yet, currently the concrete class will still inherit from ABC.

Aye, ABCs are definitely a case where I think it would be valuable to have a class decorator that:

  1. Transplants any concrete method implementations from the ABC
  2. Ensures that the class being defined actually implements all the required abstract methods

The register method doesn't do either of those things, while inheritance has the unwanted side-effect of changing the metaclass of even concrete subclasses.

As a handwavey concept, something like:

@abc.implements(collections.Mapping)
class MyMapping:
    ... # Just implement the abstract methods, get the rest injected

So I am personally more and more leaning towards a metaclass-free future.

I agree with this view in the sense that I'd like the number of use cases that require a custom metaclass to get ever smaller (replacing them with regular inheritance + definition time method injection), but I also think they'll always have a place as a way for folks to explore the design space of what's possible given full control over the class definition process.

That way, proposals like init_subclass and set_name can be based on pattern extraction from cases where people have decided the feature was valuable enough to be worth the hassle of maintaining a custom metaclass.

Cheers, Nick.

-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20171013/7921b475/attachment.html>



More information about the Python-Dev mailing list