how to unimport something

s713221 at student.gu.edu.au s713221 at student.gu.edu.au
Sun Feb 18 09:15:00 CET 2001


Sean 'Shaleh' Perry wrote:
> 
> Suppose I have a program which has logical segments.  How do I run each segment
> and have modules loaded in that segment get unloaded when I reach the next
> one?

The direct answer is

Import a module into python
>>>import modulename

Delete a module
>>>del modulename

Mind you, you may want to post to the group an example of what you're
doing. Importing modules can take some time to load in, they may be able
to suggest a more efficient and safer method than module swapping to do
what it is you're trying to do.

If you're trying to do what I think you're doing, which is have a series
of modules with similar named functions, and dynamically "plug/unplug"
them from the interpreter, a better way may be to:

>>>import modulea,moduleb,modulec (Import all your plugin modules at the start, drop the cost of module import into startup.)

>>>module = modulea
>>>module.function() (Which is actually modulea.function())
>>>module = moduleb
>>>module.function() (Which is actually moduleb.function())
>>>module = modulec
>>>module.function() (Which is actually modulec.function())
Unless you had the same functions and classes in each module, and they
could accept each others argument patterns, there's the risk of your
script failing because a piece of calling code called module.function()
expecting modulea, but getting moduleb. Messy

If you were planning to add different functionalities to the interpreter
at the same time and remove that functionality later, you would
seriously risk writing code that calls modulea functionality, only to
crash your script because another piece of code wiped out modulea
earlier.

Finally, if you're thinking to only have the modules you need loaded
into the interpreter at any time, this may save some memory, but will
cost you in module loading time. Usually not worth it unless you're
writing scripts which eg. run for days on a resource-scarce server and
it only swaps modules a couple of times a day, or are running the
scripts in a severely memory scarce environment.

Joal Heagney/AncientHart



More information about the Python-list mailing list