[Python-ideas] A (meta)class algebra

Steven D'Aprano steve at pearwood.info
Thu Feb 12 11:58:31 CET 2015


On Thu, Feb 12, 2015 at 11:09:24AM +0100, Martin Teichmann wrote:
> Hi list,
> 
> metaclasses are a really cool thing in python. Unfortunately, it can
> easily get out of hand if you use them too much, once one wants to
> inherit from two classes with different metaclasses one has to go
> some lengths to get things going again. On one hand this is
> unavoidable, as python has no way to guess how two metaclasses
> are to be mixed.
> 
> Often, however, two metaclasses are designed to work together.
> But currently, there is no way to tell the metaclass machinery how
> to mix them.
> 
> I propose to use the + operator to mix metaclasses. This means
> one can simply overwrite __add__ to get a new metaclass mixing
> behavior.

Why the + operator? This doesn't seem to have anything to do with 
addition, or concatentation. Your default implementation of __add__ 
shows that this has nothing to do with anything remotely like the 
standard use of plus:

> def __add__(self, other):
>     if issubclass(self, other):
>         return self
>     return NotImplemented

So why use + instead of ^ or % or ** ? They all seem equally arbitrary.

Just overriding __add__ (or whatever method used) doesn't solve the 
problem. You still have to actually make the metaclasses compatible, so 
that it is meaningful to mix the metaclasses. You wrote:

> They can be easily overwritten to get a different metaclass mixing
> behavior.

I question how easy that would be. If I have understood your proposal 
for metaclass __add__, mc1 + mc2 would have to return a new metaclass, 
mc3, which somehow combines behaviour from the two arguments. Even with 
cooperative metaclasses designed to work together, that sounds to me 
like it would be painful.


-- 
Steve


More information about the Python-ideas mailing list