[Python-Dev] Proposal: defaultdict

Aahz aahz at pythoncraft.com
Mon Feb 20 23:10:16 CET 2006


On Mon, Feb 20, 2006, Alex Martelli wrote:
> On Feb 20, 2006, at 12:38 PM, Aahz wrote:
>     ...
>>> Can you say, for the record (since nobody else seems to care), if
>>> d.getorset(key, func) would work in your use cases?
>>
>> Because I haven't been reading this thread all that closely, you'll  
>> have
>> to remind me what this means.
> 
> Roughly the same (save for method/function difference) as:
> 
> def getorset(d, key, func):
>    if key not in d: d[key] = func()
>    return d[key]

That has the problem of looking clumsy, and doubly so for our use case
where it's an attribute-based dict.  Our style relies on the clean look
of code like this:

    if order.street:
        ...

Even as a dict, that doesn't look horrible:

    if order['street']:
        ...

OTOH, this starts looking ugly:

    if order.get('street'):
        ...

And this is just plain bad:

    if getattr(order, 'street'):
        ...

Note that because we have to deal with *both* the possibility that the
attribute/key may not be there *and* that it might be blank -- but both
are semantically equivalent for our application -- there's no other
clean coding style.

Now, I realize this is different from the "primary use case" for needing
mutable values, but any proposed default dict solution that doesn't
cleanly support my use case is less interesting to me.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"19. A language that doesn't affect the way you think about programming,
is not worth knowing."  --Alan Perlis


More information about the Python-Dev mailing list