John Posner wrote:
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.
I just went and read the entry that had the bogus claim -- personally, I
didn't see any confusion. I would like to point out the __missing__ is
*not* part of dicts (tested on 2.5 and 2.6 -- don't have 2.7 installed yet).
Having said that, I think your final paragraph is better than my first
paragraph edit.
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
I think it's more along these lines:
class defaultdict(dict):
def __init__(self, factory=None, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.default_factory = factory
def __missing__(self, key):
"provide value for missing key"
if self.default_factory is None:
raise KeyError("blah blah blah")
value = self.default_factory()
self[key] = value
return value
~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list