[Python-Dev] Proposal: defaultdict

Adam Olsen rhamph at gmail.com
Sat Feb 18 00:08:35 CET 2006


On 2/17/06, "Martin v. Löwis" <martin at v.loewis.de> wrote:
> Adam Olsen wrote:
> > Still -1.  It's better, but it violates the principle of encapsulation
> > by mixing how-you-use-it state with what-it-stores state.  In doing
> > that it has the potential to break an API documented as accepting a
> > dict.  Code that expects d[key] to raise an exception (and catches the
> > resulting KeyError) will now silently "succeed".
>
> Of course it will, and without quotes. That's the whole point.

Consider these two pieces of code:

if key in d:
  dosomething(d[key])
else:
  dosomethingelse()

try:
  dosomething(d[key])
except KeyError:
  dosomethingelse()

Before they were the same (assuming dosomething() won't raise
KeyError).  Now they would behave differently.

The latter is even the prefered form, since it only invokes a single
dict lookup:

On 2/16/06, Delaney, Timothy (Tim) <tdelaney at avaya.com> wrote:
>     try:
>         v = d[key]
>     except:
>         v = d[key] = value

Obviously this example could be changed to use default_factory, but I
find it hard to believe the only use of that pattern is to set default
keys.

Of course you could just assume that of all the people passing your
function a dict, none of them will ever use the default_factory when
they build the dict.  Should be easy, right?

--
Adam Olsen, aka Rhamphoryncus


More information about the Python-Dev mailing list