[Tutor] How to un-import modules?
Michael P. Reilly
arcege at gmail.com
Mon Aug 14 17:46:08 CEST 2006
On 8/14/06, Dick Moores <rdm at rcblue.com> wrote:
> Actually, my question is, after using IDLE to do some importing of
> modules and initializing of variables, how to return it to it's
> initial condition without closing and reopening it.
> So, for example after I've done
> >>> import math, psyco
> >>> a = 4**23
> How can I wipe those out without closing IDLE?
> (I used to know how, but I've forgotten.)
Usually this entails removing from the "module registry and removing
references to it in the code. If you have a _really_ well used module (like
one with config parameters imported into every module), then you'll have an
additional step of removing it from every module. Also, if you have use
"from psyco import ...", then you will not be able to free up the module and
the reference to the module easily (is it from that module, or imported from
a third module? see "if paranoid: code below).
The function below deletes a module by name from the Python interpreter, the
"paranoid" parameter is a list of variable names to remove from every other
module (supposedly being deleted with the module). Be VERY careful with the
paranoid param; it could cause problems for your interpreter if your
functions and classes are named the same in different modules. One common
occurrance of this is "error" for exceptions. A lot of libraries have one
"catch-all" exception called "error" in the module. If you also named your
exception "error" and decided to include that in the paranoid list... there
go a lot of other exception objects.
def delete_module(modname, paranoid=None):
from sys import modules
thismod = modules[modname]
these_symbols = dir(thismod)
paranoid[:] # sequence support
raise ValueError('must supply a finite list for paranoid')
these_symbols = paranoid[:]
for mod in modules.values():
for symbol in these_symbols:
if symbol[:2] == '__': # ignore special symbols
Then you should be able to use this like:
delete_module('psyco', ['Psycho', 'KillerError']) # only delete these
symbols from every other module (for "from psyco import Psycho, KillerError"
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor