Looking for magic method to override to prevent dict(d) from grabbing subclass inst d contents directly

Mike Meyer mwm at mired.org
Tue Nov 22 23:46:12 EST 2005


bokr at oz.net (Bengt Richter) writes:
>>I'm not sure exactly what you mean by "grabbing sublass inst d contens
>>directly", but if dict(d.items()) does it, the above class should do
>>it as well. Of course, *other* ways of initializing a dict won't work
>>for this class.
>>
> It's not initializing the dict subclass that is a problem, it is passing
> it to the plain dict builtin as a constructor argument and being able to
> control what is pulled from the subclass object to do the construction
> of the ordinary dict.

Ah, I got it backwards.

In looking through the dict sources in 2.4.2, it looks like the
initializer creates the new dictionary, then calls the C update for
dictionary it was passed. Update checks to see if the "other" is a
real dictionary, and if so assumes that it can just use the C code for
a dict for performance reasons. So there's no way to do what you're
trying to do. You either have to not pass the dictionary, or not
subclass dictionary. You might subclass UserDict.

IIRC, there are other places where this kind of thing happens:
specifically with files before.

             <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list