[Python-ideas] A (meta)class algebra

Martin Teichmann lkb.teichmann at gmail.com
Fri Feb 13 12:51:59 CET 2015


Hi again,

let me elaborate a bit more about the changes I am proposing:
once my idea is in place, it would, for example, be possible to
have a metaclass that knows about other metaclasses.

Take the example of a metaclass like the one used by traits,
let's call it MetaTraits. Then one would be able to register
another class, for example MetaABC, as such:

    MetaTraits.registerSimpleClass(MetaABC)

this would mean that MetaTraits and MetaABC are compatible
to the point that they can be seamlessly combined. Another
metaclass, ComplicatedMeta, may be added like this:

   class CombinedMeta(ComplicatedMeta, MetaTraits):
        # add some magic here
    MetaTraits.registerClass(CombinedMeta)

an implementation of MetaTraits follows:

class MetaTraits(type):
    # add the actual traits magic

    compatible_classes = {}

    @classmethod
    def __add__(cls, other):
        ret = super().__add__(other)
        if ret is not NotImplemented:
            return ret
        return cls.compatible_classes.get(other, NotImplemented)

    @classmethod
    def registerSimpleClass(cls, other):
        class Combined(cls, other):
            pass
        cls.compatible_classes[other] = Combined

    @classmethod
    def registerClass(cls, other):
        assert cls in other.__bases__
        for b in other.__bases__:
            if cls is not b:
                cls.compatible_classes[b] = other


More information about the Python-ideas mailing list