[Python-Dev] Proposal: defaultdict
Thomas Heller
theller at python.net
Fri Feb 17 21:18:42 CET 2006
More information about the Python-Dev mailing list
Fri Feb 17 21:18:42 CET 2006
- Previous message: [Python-Dev] Stackless Python sprint at PyCon 2006
- Next message: [Python-Dev] Proposal: defaultdict
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
[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 default_factory slot initialized to None. The implementation >>> is like this (but in C): >>> >>> def on_missing(self, key): >>> if self.default_factory is not None: >>> value = self.default_factory() >>> 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.on_missing(key) and >>> returns whatever it returns -- or raises whatever it raises. >>> __getitem__() doesn't need to raise KeyError any more, that's done by >>> on_missing(). >> Will this also work when PyDict_GetItem() 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
- Previous message: [Python-Dev] Stackless Python sprint at PyCon 2006
- Next message: [Python-Dev] Proposal: defaultdict
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-Dev mailing list