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

Martin Teichmann lkb.teichmann at gmail.com
Fri Oct 13 05:35:17 EDT 2017


> 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. The following way of writing ABCs looks much
nicer to me:

    @abstractclass
    class Spam:
        @abstractmethod
        def ham(self):
             ...

The same holds for enums. Inheriting from enums is possible, but
weird, given that you cannot add new enums to it. So, especially when
comparing to the dataclasses, the following looks appealing to me:

    @enum
    class Breakfast:
        spam = 0
        ham = 1

I'm not an expert on ORMs, but they seem to me a lot like data classes
in the context of this discussion.

I am aware that currently some things are easier done with
metaclasses. But given that decorators can create an entirely new
class if they like, they have all the power to do what they want, and
even in a way much easier understood by people.

As an example, here the autoslot decorator:

    def autoslot(cls):
        """turn all class variables into slots"""
        cls.__slots__ = list(cls.__dict__)
        return type(cls.__name__, cls.__bases__, class.__dict__)

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

Cheers

Martin


More information about the Python-Dev mailing list