what is wrong with d.clear()?

Terry Reedy tjreedy at udel.edu
Mon Dec 22 03:58:02 EST 2014


On 12/21/2014 2:28 AM, shawool wrote:
> where am i going wrong ?

You clear sys.modules, which apparently CPython uses in its normal function.


> Python 3.2.5 (default, Oct  2 2013, 22:58:11)

>>>> d = {}
>>>> import sys
>>>> d = sys.modules
>>>> type(d)
> <class 'dict'>
>>>> dir(d)
> ['__class__', '__contains__', '__delattr__', '__delitem__', '__doc__',
> '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
> '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
> '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
> '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__',
> '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys',
> 'pop', 'popitem', 'setdefault', 'update', 'values']

dir(d) is the contents of d.__dict__, not d itself, so the above is not 
what you clear.  Just type d to see what is cleared.

>>>> d.clear()
> Traceback (most recent call last):dir(
>    File "<stdin>", line 1, in <module>

There is no code line because the exception in in C code.  3.4.2 gives 
more info: RuntimeError: lost builtins module.  Do upgrade if you can.

In Idle, this executes 'ok', without an exception, because it clears 
sys.modules in the user process, not the Idle process.

>>>> d
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>

However, this throws the user process into a loop, literally.

-- 
Terry Jan Reedy




More information about the Python-list mailing list