[Python-Dev] defaultdict proposal round three (original) (raw)

Guido van Rossum guido at python.org
Tue Feb 21 03:06:13 CET 2006


On 2/20/06, Guido van Rossum <guido at python.org> wrote:

[stuff with typos]

Here's the proofread version:

I have a patch ready that implements this. I've assigned it to Raymond for review. I'm just reusing the same SF patch as before: http://python.org/sf/1433928 .

One subtlety: for maximal flexibility and speed, the standard dict type now defines an on_missing(key) method; however this version just raises KeyError and the implementation actually doesn't call it unless the class is a subtype (with the possibility of overriding on_missing()).

collections.defaultdict overrides on_missing(key) to insert and return self.default_factory() if it is not None; otherwise it raises KeyError. (It should really call the base class on_missing() but I figured I'd just in-line it which is easier to code in C than a super-call.)

The defaultdict signature takes an optional positional argument which is the default_factory, defaulting to None. The remaining positional and all keyword arguments are passed to the dict constructor. IOW:

d = defaultdict(list, [(1, 2)])

is equivalent to:

d = defaultdict() d.default_factory = list d.update([(1, 2)])

At this point, repr(d) will be:

defaultdict(<type 'list'>, {1: 2})

Once Raymond approves the patch I'll check it in.

-- --Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-Dev mailing list