Why defaultdict?

Thomas Jollans thomas at jollans.com
Fri Jul 2 05:32:09 EDT 2010


On 07/02/2010 11:26 AM, Chris Rebert wrote:
> 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.
> 

Sorry Raymond, I didn't see you.

This is where I cancel my "filter out google groups users" experiment.



More information about the Python-list mailing list