On 2/20/06, Steven Bethard <steven.bethard@gmail.com> wrote:
I wrote:
# I want to do ``dd[item] += 1``
Guido van Rossum wrote:
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.
Alex Martelli wrote:
I see d[k]+=1 as a substantial improvement -- conceptually more direct, "I've now seen one more k than I had seen before".
Guido van Rossum wrote:
Yes, I now agree. This means that I'm withdrawing proposal A (new method) and championing only B (a subclass that implements __getitem__() calling on_missing() and on_missing() defined in that subclass as before, calling default_factory unless it's None).
Probably already obvious from my previous post, but FWIW, +1.
Two unaddressed issues:
* What module should hold the type? I hope the collections module isn't too controversial.
* Should default_factory be an argument to the constructor? The three answers I see:
- "No." I'm not a big fan of this answer. Since the whole point of creating a defaultdict type is to provide a default, requiring two statements (the constructor call and the default_factory assignment) to initialize such a dictionary seems a little inconvenient. - "Yes and it should be followed by all the normal dict constructor arguments." This is okay, but a few errors, like ``defaultdict({1:2})`` will pass silently (until you try to use the dict, of course). - "Yes and it should be the only constructor argument." This is my favorite mainly because I think it's simple, and I couldn't think of good examples where I really wanted to do ``defaultdict(list, some_dict_or_iterable)`` or ``defaultdict(list, **some_keyword_args)``. It's also forward compatible if we need to add some of the dict constructor args in later.
While #3 is my preferred solution as well, it does pose a Liskov violation if this is a direct dict subclass instead of storing a dict internally (can't remember the name of the design pattern that does this). But I think it is good to have the constructor be different since it does also help drive home the point that this is not a standard dict. -Brett