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

MRAB google at mrabarnett.plus.com
Mon Sep 22 20:12:35 EDT 2008


On Sep 22, 11:07 pm, CapnBearbo... at googlemail.com wrote:
> On Sep 22, 5:52 pm, Matimus <mccre... at gmail.com> wrote:
>
>
>
> > On Sep 22, 2:31 pm, CapnBearbo... at googlemail.com wrote:
>
> > > hi all,
>
> > > 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__']
>
> > > thanks,
> > >    1 desperate snake oil programmer ....
>
> > I don't think you will find anything. The interpreter is essentially
> > the same whether you are in interactive mode or not. That is, there is
> > very little use for a method that clears globals in general, so why
> > would we add it just so that it could be used by the interpreter.
> > There is almost* nothing available to the interactive interpreter
> > which isn't part of the core language.
>
> > * The only difference I can think of is the "_" variable, which is
> > added to __builtins__ and contains the last value returned in
> > interactive mode. If you have ever tried to run code that uses the
> > locale module from the interpreter you will see why having any
> > differences between the interactive and non-interactive interpreter
> > can be a pain.
>
> > Matt
>
> ok. thanks! guess i'll be off to define my own function ...

How about something like this:

def clear_workspace():
    keep_set = set(['__builtins__', '__doc__', '__name__',
'clear_workspace'])
    for x in globals().keys():
        if x not in keep_set:
            del globals()[x]



More information about the Python-list mailing list