On Tue, 22 Nov 2005 09:30:49 -0500, Mike Meyer <[EMAIL PROTECTED]> wrote:
>[EMAIL PROTECTED] (Bengt Richter) writes: >> Has anyone found a way besides not deriving from dict? >> Shouldn't there be a way? >> TIA >> (need this for what I hope is an improvement on the Larosa/Foord OrderedDict >> ;-) >> >> I guess I can just document that you have to spell it dict(d.items()), but >> I'd >> like to hide the internal shenanigans ;-) > >So why not just hide them: > >>>> class md(dict): >... def __new__(cls, arg): >... return dict.__new__(cls, arg.items()) > > >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. Here's where I am on this: (odictb is my version of odict ;-) >>> from odictb import OrderedDict >>> d = OrderedDict() >>> d['a'] = 1 >>> d['b'] = 2 >>> d {'a': 1, 'b': 2} >>> dict(d.items()) {'a': 1, 'b': 2} Looks normal, but I am secretly using key:(insertionseqno, value) to represent key:value >>> dict(d) {'a': (0, 1), 'b': (1, 2)} and I want to control dict(d) that so the result is like dict(d.items()) above. The dict builtin apparently skips looking for methods in the dict subclass. If it were a subclass of object, dict would probably be looking for __iter__ or __getitem__ or __???___ but with a dict subclass it seems to bypass such a check. I was hoping that even so there might be a __???__ that I didn't know about. [Oop, just discovered a bug in my implementation ;-/ Hope it doesn't ripple...] Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list