[Python-ideas] Allow non-callable default_factory for defaultdict

Georg Brandl g.brandl at gmx.net
Tue Jun 3 01:15:53 CEST 2008

Brandon Mintern schrieb:

> I can see one drawback to this: there is a risk of people using
> defaultdict([]) instead of defaultdict(list) with the idea that they
> will do the same thing. I think this problem can be easily overcome in
> the defaultdict documentation by specifically mentioning such a case
> as a gotcha while also using an example with a non-callable that shows
> how it is similar to using dict.get(...).

I think this was exactly one of the reasons that defaultdict takes a
factory function.  Using a list as the default is a very common use
case, and here (as opposed to function parameter defaults) we *can*
prevent endless streams of programmers falling into a "trap".

Also, this is exactly the kind of situation where lambda fits perfectly.
Since we have and keep lambda, I see no reason to complicate the API.

This should be documented with defaultdict though. I see an example
for a constant default value, but it uses itertools.repeat (!?)


More information about the Python-ideas mailing list