[IPython-dev] replacement for deep_reload.py

Ralf Schmitt ralf at brainbot.com
Wed Oct 1 13:21:57 CDT 2003


Hi,
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
__builtin__.__import__.
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):
        reloaded[name]=1
        print "Reloading", name
        __builtin__.reload(old_modules[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., 
resetting
    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]
            reloaded[ex]=1

    builtin_import = __builtin__.__import__
    __builtin__.__import__ = my_import_hook
    try:
        return __builtin__.reload(module)
    finally:
        __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]
            else:
                #print "NOT RESTORING", m
                pass




More information about the IPython-dev mailing list