Search code examples
pythoninheritancemetaclassmonkeypatching

Adding base class to existing object in python


I have several objects of different kinds (different function names, different signatures) and I monkey patch them to have a common way to access them from different functions. Briefly, there is a dispatcher that takes the objects that I want to patch and depending on the object type it calls different patcher. A patcher will add methods to the object:

def patcher_of_some_type(object):

    def target(self, value):
        # do something and call self methods

    object.target = types.MethodType(target, object)

    # many more of these

As the program grows more complicated making a wrapper around the object (or the object class) seems to be better idea. Some patchers share common code or are interrelated. But I do not control the object creation, nor the class creation. I only get the objects. And even if I could do that, I just want to wrap (or patch) certain objects, not all.

One solution might be add a base class to an existing object, but I am not sure how maintainable and safe this is. Is there another solution?


Solution

  • Dynamically modifying an object's type is reasonably safe, as long as the extra base class is compatible (and you'll get an exception if it isn't). The simplest way to add a base class is with the 3-argument type constructor:

    cls = object.__class__
    object.__class__ = cls.__class__(cls.__name__ + "WithExtraBase", (cls, ExtraBase), {})