[Python-Dev] dict.addlist() (original) (raw)
Fred L. Drake, Jr. fdrake at acm.org
Tue Jan 20 10:11:07 EST 2004
- Previous message: [Python-Dev] dict.addlist()
- Next message: [Python-Dev] Re: dict.addlist()
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Regarding d.setdefault(k, factory=list).append(v):
Moore, Paul writes:
How is it more expressive than d.setdefault(k, []).append(v)? As far as I can see, it's longer and contains an extra obscure(ish) term (factory).
The advantage I see is that it delays creation of the object being used as the default value; no list is created unless needed, whereas the setdefault() invocation shown always creates a new list, even if it's going to be thrown away. In many situations, if you're really using a list, this doesn't matter, but in other cases, especially if you're using a more complex object (or one with a more expensive constructor), using the factory makes a lot of sense.
The idea that "factory" is an obscure term for Python programmers is scary.
And I agree with the other posters that other defaults are often useful, and further complicating the dictionary interface isn't particularly helpful.
The basic setdefault() certainly remains useful on its own; I don't think anyone suggested otherwise.
My objection is the complication of the dictionary interface; it has a lot of methods now, and avoiding new names with highly specialized meanings is good.
-1 for addlist(k, v) -0 for setdefault(k, factory=...)
If conciseness is important,
def addlist(d, k, v): d.setdefault(k, []).append(v)
Yep. Or whatever variation makes sense in context.
-Fred
-- Fred L. Drake, Jr. PythonLabs at Zope Corporation
- Previous message: [Python-Dev] dict.addlist()
- Next message: [Python-Dev] Re: dict.addlist()
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]