Why can "exec ... in d" delete items from d?

Troels Therkelsen t_therkelsen at hotmail.com
Tue Aug 27 21:14:20 CEST 2002

Observe this code:

Python 2.2.1 (#1, Jun 27 2002, 10:29:04)
[GCC 2.95.3 20010315 (release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Dict(dict):
...   def __delitem__(self, key):
...     raise "not allowed to delete this item (%s)" % key
>>> d = Dict()
>>> d['foo'] = 'bar'
>>> d
{'foo': 'bar'}
>>> del d['foo']
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in __delitem__
not allowed to delete this item (foo)
>>> id(d)
>>> id(d['foo'])
>>> exec "print id(foo)" in d
>>> exec "del foo" in d
>>> d.keys()

The docs say that the implementation may or may not add __builtins__ to the
dictionary used in exec, so that is ok.

What I do not understand is why it's possible to delete an item from a
dictionary just because it happens to be used as a global namespace for

Have I stumbled unto an esoteric bug, or is this just an undocumented
feature of exec?


Troels Therkelsen

More information about the Python-list mailing list