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

Aaron "Castironpi" Brady castironpi at gmail.com
Tue Sep 23 00:51:56 CEST 2008


On Sep 22, 5:44 pm, Terry Reedy <tjre... at udel.edu> wrote:
> CapnBearbo... 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

I guess you have a few hackish options.

1) Define a wrapper that calls its argument immediately, and use it as
you would use anonymous blocks.

@call_imm
def block( ):
   code
   code
   code

@call_imm
def block( ):
   code
   code
   code

You have no globals when you are done.

2) If you need them to be global, use some introspection, and delete
the variables upon exiting the scope.

3) Declare all your variables in a namespace, and just delete the
namespace.

a= type('blank',(),{})()
a.varA= 0
a.varB= 'abc'
del a




More information about the Python-list mailing list