I have a strange and unusual use case for metaclasses where I would like to change the __metaclass__ base class after defining it, so that its subclasses will automatically use the new __metaclass__ . But this strangely doesn't work:
class MetaBase(type): def __new__(cls, name, bases, attrs): attrs["y"] = attrs["x"] + 1 return type.__new__(cls, name, bases, attrs) class Foo(object): __metaclass__ = MetaBase x = 5 print (Foo.x, Foo.y)
What I am doing can be very unreasonable / unsupported / undefined, but I canโt understand for life how the old metaclass is called, and I would like to least understand how this is possible.
EDIT: Based on the assumption of jsbueno , I replaced the line Foo.__metaclass__ = MetaSub following line, which did exactly what I wanted:
Foo = type.__new__(MetaSub, "Foo", Foo.__bases__, dict(Foo.__dict__))
source share