[Python-Dev] collections module

Martin v. Loewis martin at v.loewis.de
Sat Jan 10 17:35:16 EST 2004


Robert Brewer wrote:
> This seems a bit too easy to do "as needed" to warrant a new builtin,
> but that's why we have proposals, I guess:
> 
> class DefaultingDict(dict):
>     
>     def __init__(self, default):
>         self.default = default
>     
>     def __getitem__(self, key):
>         return self.get(key, self.default())

It would not necessarily have to be a builtin, but it should be part
of the standard library somewhere. Having to write it anew everytime
you need it is too tedious, so I usually have a try:except: block,
doing the defaulting in the except: part.

There would be also more semantic issues, such as whether has_key
should always return True on a DefaultingDict. Your implementation
is incomplete, too - .pop() should invoke the default function, as
should .get().

Regards,
Martin




More information about the Python-Dev mailing list