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

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


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 PyDict_GetItem() does not find the key?

Thomas



More information about the Python-Dev mailing list