Force python interpreter to reload a code module Force python interpreter to reload a code module python python

Force python interpreter to reload a code module


The reload built-in function will reload a single module. There are various solutions to recursively reload updated packages; see How to re import an updated package while in Python Interpreter?

Part of the issue is that existing objects need to be adjusted to reference the new classes etc. from the reloaded modules; reimport does this reasonably well. In the IPython interactive console I use the autoreload extension, although it's not designed for use outside IPython.


UPDATE: since v8 the Odoo server provides an --auto-reload option to perform this.

Excellent question, I've often wondered the same. I think the main problem with the code you posted is that it only reloads the OpenERP module's __init__.py file, not all the individual files. The reimport module recommended by ecatmur takes care of that, and I also had to unregister the module's report parsers and model classes before reloading everything.

I've posted my module_reload module on Launchpad. It seems to work for changes to model classes, osv_memory wizards, and report parsers. It does not work for old-style wizards, and there may be other scenarios that don't work.

Here's the method that reloads the module.

def button_reload(self, cr, uid, ids, context=None):    for module_record in self.browse(cr, uid, ids, context=context):        #Remove any report parsers registered for this module.        module_path = 'addons/' + module_record.name        for service_name, service in Service._services.items():            template = getattr(service, 'tmpl', '')            if template.startswith(module_path):                Service.remove(service_name)        #Remove any model classes registered for this module        MetaModel.module_to_models[module_record.name] = []                            #Reload all Python modules from the OpenERP module's directory.        modulename = 'openerp.addons.' + module_record.name        root = __import__(modulename)        module = getattr(root.addons, module_record.name)        reimport(module)    RegistryManager.delete(cr.dbname)    RegistryManager.new(cr.dbname)    return {}


ipython has a deepreload module, the documentation is here : http://ipython.org/ipython-doc/stable/api/generated/IPython.lib.deepreload.html#module-IPython.lib.deepreload

I think it's usable outside of the ipython REPL.