"specialdict" module

Georg Brandl g.brandl at gmx.net
Sun Apr 3 17:05:07 EDT 2005


Michael Spencer wrote:

> 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

I think I like Jeff's approach more (defaultvalues are just special
cases of default factories); there aren't many "hoops" required.
Apart from that, the names just get longer ;)

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

Too much specialcased for my liking.

> 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__")

I thought about this too (providing a singleton instance named Default,
just like None is, and using it as a key), but you would have to
special-case the (iter)keys,values,items methods to exclude the default
- definitely too much work, and too much magic.

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

Yes, I think this could be reasonable.

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

They aren't necessary any longer.

Use defaultdict.setdefaultvalue(0) instead of the tally approach and
defaultdict.setdefaultfactory(list) instead of listappend.

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

Any other opinions on this?

Thanks for the comments,

mfg
Georg



More information about the Python-list mailing list