default behavior

Christian Heimes lists at cheimes.de
Tue Aug 3 17:47:23 EDT 2010


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

Your proposal sounds like a good idea.

By the way do you have a CS degree? Your wording sounds like you are
used write theses on a CS degree level. No offense. ;)

> 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

defaultdict is implemented in C. You can read up the source code at
http://svn.python.org/view/python/trunk/Modules/_collectionsmodule.c?revision=81029&view=markup
. Search for "defaultdict type". The C code isn't complicated. You
should understand the concept even if you are not familiar with the C
API of Python.

> 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

The type also implements __repr__(), copy() and __reduce__(). The latter
is used by the pickle protocol. Without a new __reduce__ method, the
default_factory would no survive a pickle/unpickle cycle. For a pure
Python implementation you'd have to add __slots__ = "default_factory",
too. Otherwise every defaultdict instance would gain an unncessary
__dict__ attribute, too.

Christian




More information about the Python-list mailing list