Reloading modules dynamically

Hung Jung Lu hungjunglu at hotmail.com
Fri Jun 16 16:21:03 EDT 2000


This is probably not the most efficient hack. But it works. Make the 
following 3 Python files, and then run M1.py. After than, modify the 
messages in M2.py and/or M3.py, and you should see the changes in real-time. 
I don't know how to write a load_module() function without the extra scope 
argument... I attempted to simplify things, but did not succeed... scope 
management was kind of tricky. The hack on __builtins__ is usually not 
recommended, but since you need load_module() all over places, I guess it's 
OK. Let me know if there is any problem.

regards,

Hung Jung

---- M1.py ----------------------------------
import sys
import time

def load_module(module_name, scope):
    if scope.has_key(module_name):
        print '... reloading ' + module_name
        reload(scope[module_name])
    else:
        print '... importing ' + module_name
        exec 'import %s' % module_name in scope

__builtins__.__dict__['load_module'] = load_module

while 1:
    load_module('M2', globals())
    M2.print_me()
    time.sleep(5.)

---- M2.py ----------------------------------
load_module('M3', globals())

def print_me():
  print 'M2 loaded nice'
  M3.print_me()

---- M3.py ----------------------------------
def print_me():
  print 'M3 loaded cool'

________________________________________________________________________
Get Your Private, Free E-mail from MSN Hotmail at http://www.hotmail.com





More information about the Python-list mailing list