I\'ve found myself in an unusual situation where I need to change the MRO of a class at runtime.
The code:
class A(object):
def __init__(self):
I've found a way to change object's class or rewrite it's mro.
The easiest way is to build a new class with type function:
def upgrade_class(obj, old_class, new_class):
if obj.__class__ is old_class:
obj.__class__ = new_class
else:
mro = obj.__class__.mro()
def replace(cls):
if cls is old_class:
return new_class
else:
return cls
bases = tuple(map(replace, mro[1:]))
old_base_class = obj.__class__
new_class = type(old_base_class.__name__, bases, dict(old_base_class.__dict__))
obj.__class__ = new_class