Importing/reloading modules

OKB (not okblacke) BrenBarn at aol.com
Thu Sep 4 01:25:02 EDT 2003


    	I'm fooling around with some MUD server code, and I want to add a 
"reload" command that will let MUD wizards reload the server modules, 
so that changes to the MUD parser and such can be effected without 
having to shut down and restart the server.

    	Now, what I want to do at the top of my main module, instead of 
just "import somemodule", is something like this:

try:
    	reload(somemodule)
except NameError:
    	import somemodule

    	. . . so that it imports the module if it's just starting up, and 
reloads it otherwise.  The problem is that I want to be able to call 
this code multiple times, so I can call it from the "reload" command.  
I can't figure out how to do this appropriately.

    	If I put the try/except in a function, it doesn't import the 
module name into the global namespace, so that's no good.  I could, of 
course, import the modules normally and write a separate function that 
reloads them, but then if I decided to import another module or remove 
one, I'd have to change both pieces of code.

    	What I want is to get one piece of code that imports modules, or 
reloads them if they're already imported, and I need to be able to 
call this code like a function, from anywhere in my program.  (There 
are also "from foo import bar" statements that I need to re-execute 
along with the reloads.)  Something like:

importFunc():
    	from foo import bar # except import it into the global namespace
    	try:
    	    	reload(baz)
    	except NameError:
    	    	import baz # except import it into the global namespace

    	Someone suggested that I fiddle with __import__, but I'm not sure 
exactly what to do, or if this is the best approach.  The 
documentation seems to suggest that simply doing __import__
('somemodule', globals(), globals()) won't actually stick the module 
name into the global namespace -- is there some way to make this 
happen, though?

-- 
--OKB (not okblacke)
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
	--author unknown




More information about the Python-list mailing list