a short-cut command for globals().clear() ??

Terry Reedy tjreedy at udel.edu
Mon Sep 22 18:44:19 EDT 2008


CapnBearbossa at googlemail.com wrote:

> forgive me , but the RTFM and Google search approaches are not
> yielding an answer on this question.  I need to know if there's a top
> level python interpreter command that clears all user variables (not
> built-ins) from the global namespace.  In other words a statement, or
> some_command_or_function(), that does this:
> 
>>>> x=3
>>>> y=4
>>>> z=[]
>>>> dir()
> ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z']
> 
>>>> some_command_or_function()
> 
>>>> dir()
> ['__builtins__', '__doc__', '__name__']

First, a WARNING to other readers deceived by the subject line. 
Globals().clear() clears everything and leaves nothing, so Capn... is 
looking for something that works that is a shortcut for deleting 
bindings one-by-one.

To your question.  The short answer is no.

In batch mode, only create what you need and delete (unbind) large 
objects that are not automatically deleted (unbound) when you are done 
with them.  Remember that only reference-counted implementations will 
guarantee immediate destruction and space-freeing when the last 
reference goes away. Check the gc module (and some posts in the 
archives) for more specialized control.

In interactive mode, restart the interpreter if you really need a clean 
slate and have too many bindings that you must delete to do something 
quick like 'del x,y,z' as in your example above.  In IDLE, cntl-F6 
restarts the shell with a clean slate.  I presume IPython has something 
similar.

tjr




More information about the Python-list mailing list