[IPython-dev] replacement for deep_reload.py

Ralf Schmitt ralf at brainbot.com
Wed Oct 1 14:21:57 EDT 2003

I've just hacked my own version of deep_reload.py.
It works by replacing sys.modules with an empty hash and installing
it's __builtin__.__import__, which just calls __builtin__.reload and the old
The only problem I've discovered so far, is that dreload(os)
doesn't work (dreload(some module which imports os) however does work).
I've tested it with python 2.3.1 and IPython from cvs.
The code is very simple, so maybe you can save yourself some headache :)
I'll use that version in the next few days, and will report on other 
problems I found..
- Ralf

import sys
import __builtin__

# Save the original hooks
builtin_import = None
old_modules = {}
reloaded = {}

def my_import_hook(name, globals=None, locals=None, fromlist=None):
    global reloaded
##     if fromlist:
##         print 'Importing', fromlist, 'from module', name
##     else:
##         print 'Importing module', name

    if old_modules.has_key(name) and not reloaded.has_key(name):
        print "Reloading", name
    return builtin_import(name, globals, locals, fromlist)

# Replacement for reload()
def reload(module, exclude=['sys', '__builtin__', '__main__']):
    """Recursively reload all modules used in the given module.  Optionally
    takes a list of modules to exclude from reloading.  The default exclude
    list contains sys, __main__, and __builtin__, to prevent, e.g., 
    display, exception, and io hooks.
    global builtin_import
    global old_modules
    global reloaded

    reloaded = {}
    old_modules = sys.modules
    sys.modules = {}
    for ex in exclude+list(sys.builtin_module_names):
        if old_modules.has_key(ex):
            sys.modules[ex] = old_modules[ex]

    builtin_import = __builtin__.__import__
    __builtin__.__import__ = my_import_hook
        return __builtin__.reload(module)
        __builtin__.__import__ = builtin_import
        for m in old_modules:
            if not sys.modules.has_key(m):
                #print "RESTORING module", m
                sys.modules[m] = old_modules[m]
                #print "NOT RESTORING", m

More information about the IPython-dev mailing list