Take this blog entry with a grain of salt because I am not claiming that this technique is going to work under all circumstances or can be used in “enterprise” software. However it is an interesting experiment and for me it did work out well so far.

Let’s say we are running an important enterprise software such as an IRC bot and we are adding functionality or fixing a bug but the bot should stay on the channel and not create annoying noise by leaving and re-joining.

The first prerequisite for hot code reloading is to put the code you want to change in a separate module because this is the entity that can be reloaded by the Python interpreter through the “reload” function. To quote from the documentation:

“When reload(module) is executed: Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time.

As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero. The names in the module namespace are updated to point to any new or changed objects.”

irc = irclib.IRC()
s = irc.server()
s.connect(server, 6667, name)
s.join(channel)
responder = ircbotlib.Responder(s, channel, name)
responder.db = db


def myreload(signum, stackframe):
   global responder
   debug("reloading module")
   try:
      py_compile.compile('ircbotlib.py', doraise=True)
   except:
      debug("syntax error")
      return
   ret = s.remove_global_handler("pubmsg", responder.pubmsg)
   del responder
   ircbotlib = sys.modules['ircbotlib']
   reload(ircbotlib)
   responder = ircbotlib.Responder(connection, channel, name)
   responder.db = db
   connection.add_global_handler("pubmsg", responder.pubmsg, 0)