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

Troels Therkelsen t_therkelsen at hotmail.com
Wed Aug 28 09:12:15 CEST 2002


In article <mailman.1030510845.11562.python-list at python.org>, Christopher A.
Craig wrote:
> "Troels Therkelsen" <t_therkelsen at hotmail.com> writes:
> 
>> Have I stumbled unto an esoteric bug, or is this just an undocumented
>> feature of exec?
> 
> Hmm, I'm not sure which it is, but it's not the bug/undocumented
> feature you think it is.  The documentation specifies that the
> namespaces should be dictionaries, not mapping types or subclasses of
> dictionaries.  So when you passed it something that was subclassed
> from dict it ran PyDict_Check() on it and then, when it passed,
> treated it like a native dict.
> 
> If there is a bug, it is that exec should have refused to use your
> non-dict like it would a mapping not subclassed from dict.
> 

Actually, I did some research on Guido's paper on the new features in 2.2,
especially on subclassing built-in types.  This is what I found:

  "... The interpreter uses an internal function to access the dictionary,
   which bypasses our __getitem__() override.  I admit that this can be
   a problem (although it is only a problem in this context, when a dict
   subclass is used as a locals/globals dictionary); it remains to be
   seen if I can fix this without compromising performance in the
   common case."

Presumably, this applies to all methods, eg., __delitem__, __iter__, etc.
And the internal function used for __delitem__ is probably PyDict_DelItem().

So I guess the end story is, yes it is an undocumented feature (or at least
documented in the wrong place), but no it is not an issue the folks behind
Python are unaware of.

I guess the only thing I can do is code around it and hope that it is
fixed eventually.

Regards,

Troels Therkelsen





More information about the Python-list mailing list