Reloading nested modules

Greg Fortune lists at gregfortune.com
Tue Jul 15 15:23:31 EDT 2003


<snip> 
> I've been intended to write something that will take a module name and
> rebind it in all namespaces that have it currently, but haven't got around
> to it.  If I ever do, I'll post it here :)
<snip

Ok, here's a fairly simple minded attempt.  I have tested it only briefly
and only in a fairly simple case (ie, no massivly nested modules), but it
seems to work ok.  I'm keeping a lookup table of parent, child
relationships as they are encountered and then reloaded so I don't think
nested imports will break it.  It can probably be made more efficient, but
I thought I'd get it out in the wild ;o)

Things it does:
        reloads nested modules

Things it does not do:
        Does not care about mem or effieciency ;o)
        Does not handle any thing imported with the form "from x import *" or 
"from x import y".  I'm not sure if those get handled automatically anyway
as I have not tested that yet.
        It doesn't register itself over the top of the regular reload function. 
This is simple to do, but I can send some notes along if someone is
interested.
        Allow for a nested reload of a single module in all the places it 
occurs. (On the surface, this looks like it may take as long as a full
nested reload, but I'm going to look into the imp module and see if there
is anything there that can speed it up.)


Feel free to offer improvements/flames.  I'm fairly thick skinned so if I've
done anything really silly, let me know ;o)

Greg Fortune
Fortune Solutions

###############################################
reload_utils.py
###############################################

import inspect


def reload_from_root(root):
    if(not inspect.ismodule(root)):
        print 'root is not a module!!  Failing.'
        print type(root)

    #Keeping lists of pairs where pairs are (parent, child) 
    #to establish module relationships and prevent 
    #circular reloads
    reload_me = [(None, root)]
    reloaded = []

    while(len(reload_me) > 0):
        tmp = reload_me.pop()

        for x in inspect.getmembers(tmp[1]):
          if(inspect.ismodule(x[1])):
            if((tmp, getattr(tmp[1], x[0])) not in reloaded):
              reload_me.append((tmp[1], getattr(tmp[1], x[0])))

        reload(tmp[1])
        reloaded.append((tmp[0], tmp[1]))

        
        
###############################################






More information about the Python-list mailing list