By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,259 Members | 1,333 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,259 IT Pros & Developers. It's quick & easy.

Importing/reloading modules

P: n/a
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:

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:

from foo import bar # except import it into the global namespace
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
Jul 18 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.