pythonfunctionpluginsdecoratorredefinition

Redefinition of class method in python


Context

I'm trying to have some "plugins" (I'm not sure this is the correct definition for this) to my code. By "plugin", I mean a module which defines a model (this is a scientific code) in such a way that its existence is enough to use it anywhere else in the code.

Of course these plugins must follow a template which uses some modules/function/classes defined in my code. Here is a small snippet for the relevant part of my code:

# [In the code]
class AllModels():
    def __init__(self):
        self.count = 0

    def register(self, name, model):
        """
        Adds a model to the code
        """
        setattr(self, name, model)
        self.count += 1
        return

class Model():
    def __init__(self, **kwargs):
        """
        Some constants that defines a model
        """
        self.a = kwargs.get("a", None)
        self.b = kwargs.get("b", None)
        # and so on...

    def function1(self, *args, **kwargs):
        """
        A function that all models will have, but which needs:
            - to have a default behavior (when the instance is created)
            - to be redefinable by the "plugin" (ie. the model)
        """
        # default code for the default behavior
        return

instance = AllModels()

and here is the relevant part of the "plugin":

# [in the plugin file]
from code import Model, instance
newmodel = Model(a="a name", b="some other stuff")

def function1(*args, **kwargs):
    """
    Work to do by this model
    """
    # some specific model-dependent work
    return

instance.register(newmodel)

Additional information and requirements

Problem

I've read many different sources of python documentation and some SO question. I only see two/three possible solutions to this problem:

  1. not declaring function1 method in Model class, but just set it as an attribute when the plugin creates a new instance of it.

    [in the plugin file]

    def function1(*args, **kwargs): # .... return newmodel.function1 = function1

and then call it whenever needed. In that case the attribute function1 in the object Model would be initiate to None probably. One caveat of that is that there is no "default behaviour" for function1 (it has to be dealt in the code, eg. testing if instance.function1 is None: ...), and an even bigger one is that I can't access self this way...

  1. using somehow the python decorators. I've never used this, and the documentation I've read is not that simple (I mean not straight forward due to the huge number of possibilities on its usage). But it seems to be a good solution. However I'm worried about its performance impact (I've read that it could slow down the execution of the decorated function/method). If this solution is the best option, then I'd like to know how to use it (a quick snippet maybe), and if it is possible to use attributes of the class Model:

    [in the plugin file]

    @mydecorator def function1(self, *args, **kwargs): """ I'm not sure I can use self, but it would be great since some attributes of self are used for some other function similar to function1... """ # some stuff using self, eg.: x = self.var **2 + 3.4 # where self.var has been defined before, eg.: newmodel.var = 100.

  2. using the module types and its MethodType... I'm not sure that is relevant in my case... but I may be wrong.


Solution

  • Well, unless I'm mistaken, you want to subclass Model. This is sort of like creating an instance of Model and replacing its function1 attribute with a function defined in the plugin module (i.e. your option 1); but it's much cleaner, and takes care of all the details for you:

    # [in the plugin file]
    from code import Model, instance
    
    class MyModel(Model):
        def function1(*args, **kwargs):
            """
            Work to do by this model
            """
            # some specific model-dependent work
            return
    
    newmodel = MyModel(a="a name", b="some other stuff")
    instance.register(newmodel)
    

    This way, all the other methods (functions "attached" to a Model instance) are inherited from Model; they will behave in just the same way, but function1 will be overridden, and will follow your customized function1 definition.