[Python-Dev] Proposal: defaultdict (original) (raw)

Thomas Heller theller at python.net
Fri Feb 17 21🔞42 CET 2006


[cc to py-dev again]

Guido van Rossum wrote:

On 2/17/06, Thomas Heller <theller at python.net> wrote:

Guido van Rossum wrote:

So here's a new proposal.

Let's add a generic missing-key handling method to the dict class, as well as a defaultfactory slot initialized to None. The implementation is like this (but in C): def onmissing(self, key): if self.defaultfactory is not None: value = self.defaultfactory() self[key] = value return value raise KeyError(key) When getitem() (and only getitem()) finds that the requested key is not present in the dict, it calls self.onmissing(key) and returns whatever it returns -- or raises whatever it raises. getitem() doesn't need to raise KeyError any more, that's done by onmissing(). Will this also work when PyDictGetItem() does not find the key? Ouch, tricky. It should, of course, but the code will be a tad tricky because it's not supposed to inc the refcount. Thanks for reminding me!

Ahem, I'm still looking for ways to 'overtake' the dict to implement weird and fancy things. Can on_missing be overridden in subclasses (writing the subclass in C would not be a problem)?

Thanks,

Thomas



More information about the Python-Dev mailing list