default behavior

John Posner jjposner at optimum.net
Tue Aug 3 17:24:53 EDT 2010


On 8/3/2010 12:54 PM, Ethan Furman wrote:

<snip>

> 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.

Thanks, Ethan. As I said (or at least implied) to Christian earlier in 
this thread, I don't want to repeat the mistake of the current 
description: confusing the functionality provided *by* the defaultdict 
class with underlying functionality (the dict type's __missing__ 
protocol) that is used in the definition of the class.

So I'd rather not mention __missing__ in the first paragraph, which 
describes the functionality provided *by* the defaultdict class. How 
about adding this para at the end:

  defaultdict is defined using functionality that is available to *any*
  subclass of dict: a missing-key lookup automatically causes the
  subclass's __missing__ method to be called, with the non-existent key
  as its argument. The method's return value becomes the result of the
  lookup.

BTW, I couldn't *find* the coding of defaultdict in the Python 2.6 
library. File collections.py contains this code:

   from _abcoll import *
   import _abcoll
   __all__ += _abcoll.__all__

   from _collections import deque, defaultdict

... but I ran into a dead end after that. :-(  I believe that the 
following *could be* the definition of defaultdict:

class defaultdict(dict):
     def __init__(self, factory, *args, **kwargs):
         dict.__init__(self, *args, **kwargs)
         self.default_factory = factory

     def __missing__(self, key):
         """provide value for missing key"""
         value = self.default_factory() # call factory with no args
         self[key] = value
         return value

-John



More information about the Python-list mailing list