Why defaultdict?

Chris Rebert clp2 at rebertia.com
Fri Jul 2 05:26:23 EDT 2010


On Fri, Jul 2, 2010 at 2:20 AM, Thomas Jollans <thomas at jollans.com> wrote:
> On 07/02/2010 06:11 AM, Steven D'Aprano wrote:
>> I would like to better understand some of the design choices made in
>> collections.defaultdict.
<snip>
>> Second, why is the factory function not called with key? There are three
>> obvious kinds of "default values" a dict might want, in order of more-to-
>> less general:
>>
>> (1) The default value depends on the key in some way: return factory(key)
>
> I agree, this is a strange choice. However, nothing's stopping you from
> being a bit verbose about what you want and just doing it:
>
> class mydict(defaultdict):
>    def __missing__(self, key):
>        # ...
>
> the __missing__ method is really the more useful bit the defaultdict
> class adds, by the looks of it.

Nitpick: You only need to subclass dict, not defaultdict, to use
__missing__(). See the part of the docs Raymond Hettinger quoted.

Cheers,
Chris



More information about the Python-list mailing list