ethan at stoneleaf.us
Tue Aug 3 18:54:46 CEST 2010
John Posner wrote:
> On 7/31/2010 1:31 PM, John Posner wrote:
>> Caveat -- there's another description of defaultdict here:
>> ... and it's bogus. This other description claims that __missing__ is a
>> method of defaultdict, not of dict.
> Following is a possible replacement for the bogus description. Comments
> welcome. I intend to submit a Python doc bug, and I'd like to have a
> clean alternative to propose.
> class collections.defaultdict([default_factory[, ...]])
> defaultdict is a dict subclass that can guarantee success on key
> lookups: if a key does not currently exist in a defaultdict object, a
> "default value factory" is called to provide a value for that key. The
> "default value factory" is a callable object (typically, a function)
> that takes no arguments. You specify this callable as the first argument
> to defaultdict(). Additional defaultdict() arguments are the same as for
> The "default value factory" callable is stored as an attribute,
> default_factory, of the newly created defaultdict object. If you call
> defaultdict() with no arguments, or with None as the first argument, the
> default_factory attribute is set to None. You can reassign the
> default_factory attribute of an existing defaultdict object to another
> callable, or to None.
> When a lookup of a non-existent key is performed in a defaultdict
> object, its default_factory attribute is evaluated, and the resulting
> object is called:
> * If the call produces a value, that value is returned as the result of
> the lookup. In addition, the key-value pair is inserted into the
> * If the call raises an exception, it is propagated unchanged.
> * If the default_factory attribute evaluates to None, a KeyError
> exception is raised, with the non-existent key as its argument. (The
> defaultdict behaves exactly like a standard dict in this case.)
I think mentioning how __missing__ plays into all this would be helpful.
Perhaps in the first paragraph, after the colon:
if a key does not currently exist in a defaultdict object, __missing__
will be called with that key, which in turn will call a "default value
factory" to provide a value for that key.
More information about the Python-list