what is wrong with d.clear()?

Ned Batchelder ned at nedbatchelder.com
Mon Dec 22 06:41:20 EST 2014


On 12/21/14 2:28 AM, shawool wrote:
> Hi,
>
> where am i going wrong ?
>
> $ python3
> Python 3.2.5 (default, Oct  2 2013, 22:58:11)
> [GCC 4.8.1] on cygwin
> Type "help", "copyright", "credits" or "license" for more information.
>>>> d = {}
>>>> import sys
>>>> d = sys.modules

This does not make a copy of sys.modules.  This make d refer to the 
actual sys.modules dictionary.

>>>> 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']
>>>> d.clear()

This cleared the contents of d, which is also sys.modules, so you have 
clobbered sys.modules.  This will make many things stop working in Python.

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

Like all of these things.

-- 
Ned Batchelder, http://nedbatchelder.com




More information about the Python-list mailing list