[Python-Dev] Proposal: defaultdict

Phillip J. Eby pje at telecommunity.com
Sat Feb 18 04:51:13 CET 2006

At 11:58 AM 02/17/2006 -0800, Guido van Rossum wrote:
>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!)

Why not a classmethod constructor:

  d = dict.with_factory(list)

Admittedly, the name's not that great.  Actually, it's almost as bad as 
setdefault in some ways.  But I'd rather set the default and create the 
dictionary in one operation, since when reading it as two, you first think 
'd is a dictionary', and then 'oh, but it has a default factory', as 
opposed to "d is a dict with a factory" in one thought.  But maybe that's 
just me.  :)

More information about the Python-Dev mailing list