Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #6965

except KeyError, everywhere

From Wilbert Berendsen <wbsoft@xs4all.nl>
Organization www.wilbertberendsen.nl
Subject except KeyError, everywhere
Date 2011-06-03 22:08 +0200
Newsgroups comp.lang.python
Message-ID <mailman.2437.1307132130.9059.python-list@python.org> (permalink)

Show all headers | View raw


Hi,

I find myself all over the place associating objects with each other using 
dicts as caches:

something like this:

_cache = {}

def get_something(obj):
    """Returns the frobnicate-plugin for the specified object."""
    try:
        return _cache[obj]
    except KeyError:
        res = _cache[obj] = LargeClass(obj)
        return res


I would like a dict that would do this by itself, so that I could write:

_cache = somelazydict(LargeClass)

def get_something(obj):
    """Returns the frobnicate-plugin for the specified object."""
    return _cache[obj]

or even using the dict directly:

plugin_store = somelazydict(LargeClass)

It seems that I can't use defaultdict for this, because it calls the factory 
function without an argument, where I need to have the key as argument.

So I came up with this (using the __missing__ dict hook since Python 2.5):

class cachedict(dict):
    """A dict, but with a factory function as the first argument.
    
    On lookup, if the key is missing, the function is called with the key as
    argument. The returned value is also stored in the dict.
    
    """
    def __init__(self, func, *args, **kwargs):
        """Creates the dict, with the factory function as the first argument.
        
        All other arguments work just like dict.
        
        """
        dict.__init__(self, *args, **kwargs)
        self.func = func
    
    def __missing__(self, key):
        res = self[key] = self.func(key)
        return res

Are there other peoply using things like this? Is there a solution like this 
in the standard lib that I'm overlooking? Of course 'except KeyError' 
everywhere is not really a big deal...

With best regards,
Wilbert Berendsen

-- 
http://www.wilbertberendsen.nl/
"You must be the change you wish to see in the world."
        -- Mahatma Gandhi

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

except KeyError, everywhere Wilbert Berendsen <wbsoft@xs4all.nl> - 2011-06-03 22:08 +0200
  Re: except KeyError, everywhere Nobody <nobody@nowhere.com> - 2011-06-04 01:02 +0100
    Re: except KeyError, everywhere --> memoization Wilbert Berendsen <wbsoft@xs4all.nl> - 2011-06-05 00:27 +0200
    Re: except KeyError, everywhere "Gabriel Genellina" <gagsl-py2@yahoo.com.ar> - 2011-06-07 00:45 -0300
      Re: except KeyError, everywhere Ben Finney <ben+python@benfinney.id.au> - 2011-06-07 14:08 +1000
  Re: except KeyError, everywhere Ben Finney <ben+python@benfinney.id.au> - 2011-06-04 10:03 +1000
    Re: except KeyError, everywhere Ben Finney <ben+python@benfinney.id.au> - 2011-06-04 10:37 +1000

csiph-web