[Tutor] Resetting the environment

Bob Gailer bgailer@alum.rpi.edu
Wed Jun 4 11:21:18 2003


At 08:44 PM 6/2/2003 -0700, Neil Schemenauer wrote:

>Tom Plunket wrote:
> > I'd basically like to undefine everything and unload all of the
> > modules.
>
>Restarting would be the easiest.  It would be possible to write a
>function that clears all modules (I think) but it would be a non-trivial
>amount of work and it's not a standard thing.

If you really want to do this, read the manual on how import works, and 
consider (untested):

1 - when you start the interpreter:

import sys
preloads = sys.modules.keys() # modules that are part of the "system" and 
should not be deleted

2 - when you want to clean up

for name in sys.modules.keys():
   if name not in preloads: # a module that was imported after startup
     del sys.modules[name] # remove reference from sys.modules
     try: eval(name + ' = None') # remove module name from namespace
     except: pass

Note that this will NOT affect names created by from xxx import .... You'd 
have to delete them explicitly

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625