halbrd
halbrd

Reputation: 135

What's the best way to implement module hot reloading in Python?

I have a Python daemon (a chat bot) that I want to be able to reload local modules while running, as those modules contain code that dictates the bot's behavior and may have been updated with new functionality. Naturally, restarting the whole bot is a very undesirable option as that would incur considerable downtime.

Currently I achieve this in this way:

module = importlib.import_module(module_name)
importlib.reload(module)

Is this the correct way to do this? Are there any problems with this approach?

Upvotes: 1

Views: 2061

Answers (1)

deeenes
deeenes

Reputation: 4576

I think it's ok how you are doing. I used to do like this. Find out the name of the module your class has been loaded from, reload that module and then replace all attributes of the instance with the corresponding ones from the reloaded class:

import imp
import somemodule

class A(object):

    def __init__(self):
        pass

    def somemethod(self):

        return somemodule.somemethod()

    def reload(self):

        imp.reload(somemodule)
        modname = self.__class__.__module__
        mod = __import__(modname, fromlist = [modname.split('.')[0]])
        imp.reload(mod)
        new = getattr(mod, self.__class__.__name__)
        setattr(self, '__class__', new)

If you need to update more than one module or class you can make it recursive. Also be aware that you need to reload all modules depending on the updated module in the order how they depend on each other. And if you used from mod import something you need to import mod, imp.reload(mod) and then reload the current module.

Upvotes: 4

Related Questions