Wilbert Berendsen <wbs...@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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to