[Python-Dev] Proposal: defaultdict

Barry Warsaw barry at python.org
Tue Feb 21 05:11:26 CET 2006

On Sat, 2006-02-18 at 12:53 +0100, Pierre Barbier de Reuille wrote:

> >     Guido> Over lunch with Alex Martelli, he proposed that a subclass of
> >     Guido> dict with this behavior (but implemented in C) would be a good
> >     Guido> addition to the language.

I agree that .setdefault() is a well-intentioned failure, although I'm
much less concerned about any potential performance impact than the fact
that it's completely unreadable.  And while I like the basic idea, I
also agree that deriving from dict is problematic, both because of the
constructor signature is tough to forward, but also because dict is such
a fundamental type that APIs that return dicts may have to be changed to
allow passing in a factory type.

I'd rather like to see what Pierre proposes, with a few minor

> Well, first not ot break the current interface, and second because I think it
> reads better I would prefer :
>       d = {'a': 1}'
>       d['b']              # raises KeyError
>       d.get('c')          # evaluates to None
>       d.default = 42
>       d['b']              # evaluates to 42
>       d.get('c')          # evaluates to 42

So far so good.

> And to undo the default, you can simply do :
>       del d.default

Although this I'm not crazy about.  If you let .default be a callable,
you could also write this as

def keyerror(): raise KeyError
d.default = keyerror

or possibly just this as a shortcut:

d.default = KeyError

> > The only question in my mind is whether or not getting a non-existent value
> > under the influence of a given default value should stick that value in the
> > dictionary or not.

Agreed.  I'm not sure whether .get(onearg) should return None
or .default.  I /think/ I want the latter, but I'd have to play with
some real code to know for sure.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 307 bytes
Desc: This is a digitally signed message part
Url : http://mail.python.org/pipermail/python-dev/attachments/20060220/3adbcbd6/attachment.pgp 

More information about the Python-Dev mailing list