[Tutor] IDLE question (original) (raw)

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