Reloading modules dynamically

Eckhard Pfluegel Eckhard at pfluegel.fsnet.co.uk
Thu Jun 15 17:20:38 EDT 2000


I am writing a Python application which consists of two parts: a server
and a client. The client sends requests to the server. The requests
contain names of modules which the server is supposed to load and to
use.
The problem is that these modules might change at runtime, and I want to
send refresh requests to the server so that it reloads the modules. The
modules contain class definitions, I know that reloading such modules is
not recommended since previously instanciated objects will continue to
exist with the old class definition. However I make sure that all these
old objects won't be used after the reload.
In order to deal with a module name stored in "name", the code on the
server side goes

m = sys.__dict__["modules"]
if not m.has_key(name):
    # this means the module is not yet loaded
    exec("import " + name)
else:
    # reload the module
    reload(m[name])

This look like a bad hack to me, but it works. But now I am running into
problems because one of the modules "m" itselfs imports another module
say "n". This other module "n" as well changes during runtime, and this
is not detected even after a refresh request because the import
statement in module "m" does not reload "n".
I wonder how I could solve that problem or, even better, whether one of
you guys out there have another idea of realising the whole matter...

Thanks very much in advance,

Eckhard






More information about the Python-list mailing list