[Tutor] IDLE question

Steve lonetwin at gmail.com
Fri Jul 9 14:47:31 CEST 2004


Hi,

On Fri, 09 Jul 2004 05:08:55 -0700, Dick Moores <rdm at rcblue.com> wrote:
> Don't know what to call it, but I'd like to know how to delete all
> variables I've created, un-import all modules I've imported, etc., with
> one command, when using IDLE interactively.

It is called deleting all the variables you have created, or modules
you have imported from the current 'namespace', which btw at the
interactive prompt is the 'global' namespace. The names of the
elements in the global namespace can be seen using the builtin
function "dir()" at the python prompt.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Python 2.3.3 (#2, Feb 17 2004, 11:45:40) 
[GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> dir()
['__builtins__', '__doc__', '__file__', '__name__']
>>> a = 10
>>> dir()
['__builtins__', '__doc__', '__file__', '__name__', 'a']
>>>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 Also, the actual contents of the global namespace can be seen using
the builtin function globals(), which returns a dictionary containing
the names of the elements as keys and the actual elements as the
values. Eg:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Python 2.3.3 (#2, Feb 17 2004, 11:45:40) 
[GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__file__':
'/home/steve/.pystartup', '__name__': '__main__', '__doc__': None}
>>>
>>> import os
>>> a = 10
>>>
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__file__':
'/home/steve/.pystartup', '__name__': '__main__', 'os': <module 'os'
from '/usr/lib/python2.3/os.pyc'>, '__doc__': None, 'a':10}
>>>
>>>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

     To delete any element from a namspace you can use the keyword del. For eg:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>>> a = 10
>>> dir()
['__builtins__', '__doc__', '__file__', '__name__', 'a']
>>> del a
>>> dir()
['__builtins__', '__doc__', '__file__', '__name__']
>>>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

So, to do what you asked for, you can simply do something like:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>>> for i in globals().keys():
...     if i not in ['__builtins__', '__doc__', '__file__', '__name__']:
...             del globals()[i]
...
>>> del i
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

HTH
Steve


More information about the Tutor mailing list