On 8/14/06, <b class="gmail_sendername">Dick Moores</b> <<a href="mailto:rdm@rcblue.com">rdm@rcblue.com</a>> wrote:<div><span class="gmail_quote"></span><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
Actually, my question is, after using IDLE to do some importing of<br>modules and initializing of variables, how to return it to it's<br>initial condition without closing and reopening it.<br><br>So, for example after I've done
<br> >>> import math, psyco<br> >>> a = 4**23<br><br>How can I wipe those out without closing IDLE?<br>(I used to know how, but I've forgotten.)</blockquote><div><br>Hi Dick,<br> 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).
<br><br>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.
<br><br>def delete_module(modname, paranoid=None):<br> from sys import modules<br> try:<br> thismod = modules[modname]<br> except KeyError:<br> raise ValueError(modname)<br> these_symbols = dir(thismod)
<br> if paranoid:<br> try:<br> paranoid[:] # sequence support<br> except:<br> raise ValueError('must supply a finite list for paranoid')<br> else:<br> these_symbols = paranoid[:]
<br> del modules[modname]<br> for mod in modules.values():<br> try:<br> delattr(mod, modname)<br> except AttributeError:<br> pass<br> if paranoid:<br> for symbol in these_symbols:
<br> if symbol[:2] == '__': # ignore special symbols<br> continue<br> try:<br> delattr(mod, symbol)<br> except AttributeError:<br> pass
<br><br>Then you should be able to use this like:<br><br>delete_module('psyco')<br> or<br>delete_module('psyco', ['Psycho', 'KillerError']) # only delete these symbols from every other module (for "from psyco import Psycho, KillerError" statements)
<br></div></div><br> -Arcege<br><br>-- <br>There's so many different worlds,<br>So many different suns.<br>And we have just one world,<br>But we live in different ones.