except KeyError, everywhere

Ben Finney ben+python at benfinney.id.au
Fri Jun 3 20:03:38 EDT 2011


Wilbert Berendsen <wbsoft at xs4all.nl> writes:

> 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

You seem to be looking for the Memoize pattern
<URL:https://secure.wikimedia.org/wikipedia/en/wiki/Memoization>.

It's best to implement Memoize as a Python decorator in one place
<URL:http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize>.

Once you have that decorator, apply it to any function you like::

    @memoized
    def get_something(obj):
        """ Returns the frobnicate-plugin for the specified object. """
        res = LargeClass(obj)
        return res

-- 
 \         “Faith may be defined briefly as an illogical belief in the |
  `\                  occurrence of the improbable.” —Henry L. Mencken |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list