Why defaultdict?

Raymond Hettinger raymond.hettinger at gmail.com
Fri Jul 2 01:06:42 EDT 2010


On Jul 1, 9:11 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> I would like to better understand some of the design choices made in
> collections.defaultdict.
 . . .
> If callable is None, defaultdicts are
> *exactly* equivalent to built-in dicts, so I wonder why the API wasn't
> added on to dict rather than a separate class that needed to be imported.
 . . .
> 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)
> (2) The default value doesn't depend on the key: return factory()
> (3) The default value is a constant: return C

The __missing__() magic method lets you provide a factory with a key.
That method is supported by dict subclasses, making it easy to
create almost any desired behavior.  A defaultdict is an example.
It is a dict subclass that calls a zero argument factory function.
But with __missing__() can roll your own dict subclass to meet your
other needs.  A defaultdict was provided to meet one commonly
requested set of use cases (mostly ones using int() and list()
as factory functions).

>From the docs at http://docs.python.org/library/stdtypes.html#mapping-types-dict
:

'''New in version 2.5: If a subclass of dict defines a method
__missing__(), if the key key is not present, the d[key] operation
calls that method with the key key as argument. The d[key] operation
then returns or raises whatever is returned or raised by the
__missing__(key) call if the key is not present. No other operations
or methods invoke __missing__(). If __missing__() is not defined,
KeyError is raised. __missing__() must be a method; it cannot be an
instance variable. For an example, see collections.defaultdict.'''

Raymond




More information about the Python-list mailing list