[Python-Dev] defaultdict proposal round three

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

On 2/20/06, Alex Martelli <aleaxit at gmail.com> wrote:
> > [Alex]
> >>> I see d[k]+=1 as a substantial improvement -- conceptually more
> >>> direct, "I've now seen one more k than I had seen before".
> >
> > [Guido]
> >> Yes, I now agree. This means that I'm withdrawing proposal A (new
> >> method) and championing only B (a subclass that implements
> >> __getitem__() calling on_missing() and on_missing() defined in that
> >> subclass as before, calling default_factory unless it's None). I don't
> >> think this crisis is big enough to need *two* solutions, and this
> >> example shows B's superiority over A.

> > FWIW, I'm happy with the proposal and think it is a nice addition
> > to Py2.5.

> OK, sounds great to me.  collections.defaultdict, then?

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:

One subtlety: for maximul 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

collections.defaultdict overrides on_missing(key) to insert and return
self.fefault_factory() if it is not empty; 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

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