defaultdict's bug or feature?

Red Forks redforks at
Fri May 22 10:53:04 CEST 2009

Yes, you maybe right. When use defaultdict, should not rely get() method
anymore, d[] is just enough. When a function return a defaultdict, but
people don't know it, so:

d = load_map()
# if she call d['a'], everything is OK but
# when call d.get('a'), she is always get None.
# Why she call d.get('a'), not d['a'], because she don't want to provider
default value herself (she didn't know it is a defaultdict)
It is just wield, call d[''a'] Ok, not get('a').

Sorry my poor english. Maybe somebody don't catch my mind, or maybe a little
I'm using and learning python about 2 weeks ago, spent me three hrs to find
the problem, almost drive me mad.
Maybe other like me, find some inconvience on this.


Actually, I steal defaultdict to do other things:

class OnloadDict(defaultdict):
    def __init__(self, onload):
        self.__onload = onload

    def __missing__(self, key):
        result = self.__onload(key)
        if not result:
            raise KeyError

        self[key] = result
        return result

    def get(self, key, default = None):
        ''' defaultdict.get() won't call __missing__, so override '''
            return self[key]
        except KeyError:
            return default

OnloadDict, is like a cache. When the value is not in dict, using 'onload'
function to load the value by the key.
When no value correspond to a key, a KeyError will raised. So I need a
*safer* version 'get()' method.

On Fri, May 22, 2009 at 12:35 PM, Rhodri James
<rhodri at>wrote:

> Please don't top-post, it makes the thread of argument hard to follow.
> On Fri, 22 May 2009 01:44:37 +0100, Red Forks <redforks at> wrote:
>  You mean 'get' method should not alter the dict, does 'dict[key]' should
>> not
>> alter the dict either?
>> d = defaultdict(set)
>> assert len(d) == 0
>> print d[1]
>> assert len(d) == 1
>> auto insert value to dict, when value is not in dict, is what defaultdict
>> try to do.
> Behaviour you are deliberately avoiding by calling `get`, since that
> explicitly behaves the same way that it does for dicts.  You're doing
> two different things through two different interfaces with two different
> specs.  Why are you expecting them to have the same effect?
> --
> Rhodri James *-* Wildebeeste Herder to the Masses
> --
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list