Search code examples
pythonreflectiontwisted

Dynamically reload a class definition in Python


I've written an IRC bot using Twisted and now I've gotten to the point where I want to be able to dynamically reload functionality.

In my main program, I do from bots.google import GoogleBot and I've looked at how to use reload to reload modules, but I still can't figure out how to do dynamic re-importing of classes.

So, given a Python class, how do I dynamically reload the class definition?


Solution

  • I figured it out, here's the code I use:

    def reimport_class(self, cls):
        """
        Reload and reimport class "cls".  Return the new definition of the class.
        """
    
        # Get the fully qualified name of the class.
        from twisted.python import reflect
        full_path = reflect.qual(cls)
    
        # Naively parse the module name and class name.
        # Can be done much better...
        match = re.match(r'(.*)\.([^\.]+)', full_path)
        module_name = match.group(1)
        class_name = match.group(2)
    
        # This is where the good stuff happens.
        mod = __import__(module_name, fromlist=[class_name])
        reload(mod)
    
        # The (reloaded definition of the) class itself is returned.
        return getattr(mod, class_name)