[Python-Dev] defaultdict proposal round three
Guido van Rossum
guido at python.org
Mon Feb 20 21:33:04 CET 2006
On 2/20/06, Steven Bethard <steven.bethard at gmail.com> wrote:
> Guido van Rossum wrote:
> > Alternative A: add a new method to the dict type with the semantics of
> > [__getitem__] from the last proposal, using default_factory if not None
> > (except on_missing is inlined).
> I'm not certain I understood this right but [...]
> this seems to suggest that for keeping a
> dict of counts the code wouldn't really improve much:
You don't need a new feature for that use case; d[k] = d.get(k, 0) + 1
is perfectly fine there and hard to improve upon.
It's the slightly more esoteric use case where the default is a list
and you want to append to that list that we're trying to improve:
currently the shortest version is d.setdefault(k, ).append(v) but
that lacks legibility and creates an empty list that is thrown away
most of the time. We're trying to obtain the minimal form
d.foo(k).append(v) where the new list is created by implicitly calling
d.default_factory if d[k] doesn't yet exist, and d.default_factory is
set to the list constructor.
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev