[Python-Dev] Proposal: defaultdict

Guido van Rossum guido at python.org
Fri Feb 17 20:58:10 CET 2006


On 2/17/06, Alex Martelli <aleaxit at gmail.com> wrote:
> On 2/16/06, Guido van Rossum <guido at python.org> wrote:
> > A bunch of Googlers were discussing the best way of doing the
>    ...
> Wow, what a great discussion!  As you'll recall, I had also mentioned
> the "callable factory" as a live possibility, and there seems to be a
> strong sentiment in favor of that; not really a "weakness case" for
> HOFs, as you feared it might be during the lunchtime discussion.

:-)

You seem to have missed my revised proposal.

> Out of all I've read here, I like the idea of having a
> collections.autodict (a much nicer name than defaultdict, a better
> collocation for 2.5 than the builtins). One point I think nobody has
> made is that whenever reasonably possible the setting of a callback
> (the callable factory here) should include *a and **k to use when
> calling back.

That's your C/C++ brain talking. :-)

If you need additional data passed to a callback (to be provided at
the time the callback is *set*, not when it is *called*) the customary
approach is to make the callback a parameterless lambda; you can also
use a bound method, etc. There's no need to complicate ever piece of
code that calls a callback with the machinery to store and use
arbirary arguments and keyword arguments.

I forgot to mention in my revised proposal that the API for setting
the default_factory is slightly odd:

  d = {}   # or dict()
  d.default_factory = list

rather than

  d = dict(default_factory=list)

This is of course because we cut off that way when we defined what
arbitrary keyword arguments to the dict constructor would do. My
original proposal solved this by creating a subclass. But there were
several suggestions that this would be fine functionality to add to
the standard dict type -- and then I really don't see any other way to
do this. (Yes, I could have a set_default_factory() method -- but a
simple settable attribute seems more pythonic!)

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


More information about the Python-Dev mailing list