[Python-Dev] defaultdict proposal round three
Ian Bicking
ianb at colorstudy.com
Mon Feb 20 22:13:27 CET 2006
Steven Bethard wrote:
>>Alternative A: add a new method to the dict type with the semantics of
>>__getattr__ from the last proposal, using default_factory if not None
>>(except on_missing is inlined).
>
>
> I'm not certain I understood this right but (after
> s/__getattr__/__getitem__) this seems to suggest that for keeping a
> dict of counts the code wouldn't really improve much:
>
> dd = {}
> dd.default_factory = int
> for item in items:
> # I want to do ``dd[item] += 1`` but with a regular method instead
> # of __getitem__, this is not possible
> dd[item] = dd.somenewmethod(item) + 1
This would be better done with a bag (a set that can contain multiple
instances of the same item):
dd = collections.Bag()
for item in items:
dd.add(item)
Then to see how many there are of an item, perhaps something like:
dd.count(item)
No collections.Bag exists, but of course one should. It has nice
properties -- inclusion is done with __contains__ (with dicts it
probably has to be done with get), you can't accidentally go below zero,
the methods express intent, and presumably it will implement only a
meaningful set of methods.
--
Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org
More information about the Python-Dev
mailing list