"specialdict" module

Michael Spencer mahs at telcopartners.com
Sun Apr 3 16:25:53 EDT 2005


Georg Brandl wrote:
> Hello,
> 
> in follow-up to the recent "dictionary accumulator" thread, I wrote a
> little module with several subclassed dicts.
> 
> Comments (e.g. makes it sense to use super), corrections, etc.? Is this
> PEP material?
> 
> Docstrings, Documentation and test cases are to be provided later.
> 
> mfg
> Georg
> 

Georg:

A few reactions:

1. Given that these are specializations, why not have:

class defaultvaluedict(dict):
     ...

class defaultfactorydict(dict):
     ...

rather than having to jump through hoops to make one implementation satisfy both 
cases

2. I would really prefer to have the default value specified in the constructor

I realize that this is tricky due to the kw arguments of dict.__init__, but I 
would favor either breaking compatibility with that interface, or adopting some 
workaround to make something like d= defaultvaluedict(__default__ = 0) possible.

One worksaround would be to store the default in the dict, not as an attribute 
of the dict.  By default the default value would be associated with the key 
"__default__", but that keyname could be changed for the (I guess very few) 
cases where that key conflicted with non-default content of the dict.  Then 
dict.__init__ would simply take __default__ = value as a keyword argument, as it 
does today, and __getitem__ for a missing key would return 
dict.__getitem__(self, "__default__")

Alternatively, you could provide factory functions to construct the defaultdict. 
  Someone (Michele?) recently posted an implementation of this

3. Can you work in the tally and listappend methods that started this whole 
thread off?

4. On super, no I don't think it's necessary or particularly desirable.  These 
specializations have a close association with dict.  dict.method(self,...) feels 
more appropriate in this case.

Michael





More information about the Python-list mailing list