defaultdict's bug or feature?

Rhodri James rhodri at wildebst.demon.co.uk
Fri May 22 14:03:04 EDT 2009


I asked you not to top-post.  Please put your replies *below* the
messages you're quoting, not above.  It's much easier to understand
the conversation that we're having if you do that, and much more
aggravating if you don't.

On Fri, 22 May 2009 09:53:04 +0100, Red Forks <redforks at gmail.com> wrote:

> Yes, you maybe right. When use defaultdict, should not rely get() method
> anymore, d[] is just enough.

Almost.  You should rely on get() to do what it says, not what you think
it should do.  That's generally true, by the way; when the Fine Manual
says that a class, function or method will do one thing, expecting it to
do something else is unreasonable.

> 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 '''
>         try:
>             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.

Why are you so determined to (ab)use get() on your class?  You should
only be calling OnloadDict.get() if you really mean "get me the value
associated with this key, or the default I'm telling you about *right*
*now* if there isn't one."

Aside from that, this is neat.  Strictly you should call
defaultdict.__init__(self) in your __init__() function just in case
defaultdict needs any setup that you aren't doing (which it does, but
you override __missing__() so it never notices that it doesn't have
a default_factory).  You get away with it here, but it's not a good
habit to get into.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list