[Baypiggies] A few decorator questions...

Benjamin Sergeant bsergean at gmail.com
Thu Feb 26 23:01:56 CET 2009

A cool decorator I found on ActiveState is one that does memoization.
It caches the results of a function in a dictionary. The key is the
parameters, the value is the return value of your function.

I use it for recursive function sometimes needed when trying to solve
computer puzzles (Project Euler :)

- Benjamin

# http://code.activestate.com/recipes/466320/
from cPickle import dumps, PicklingError # for memoize
class memoize(object):
    """Decorator that caches a function's return value each time it is called.
    If called later with the same arguments, the cached value is returned, and
    not re-evaluated. Slow for mutable types."""
    # Ideas from MemoizeMutable class of Recipe 52201 by Paul Moore and
    # from memoized decorator of
    # For a version with timeout see Recipe 325905
    # For a self cleaning version see Recipe 440678
    # Weak references (a dict with weak values) can be used, like this:
    #   self._cache = weakref.WeakValueDictionary()
    #   but the keys of such dict can't be int
    def __init__(self, func):
        self.func = func
        self._cache = {}
    def __call__(self, *args, **kwds):
        key = args
        if kwds:
            items = kwds.items()
            key = key + tuple(items)
            if key in self._cache:
                return self._cache[key]
            self._cache[key] = result = self.func(*args, **kwds)
            return result
        except TypeError:
                dump = dumps(key)
            except PicklingError:
                return self.func(*args, **kwds)
                if dump in self._cache:
                    return self._cache[dump]
                self._cache[dump] = result = self.func(*args, **kwds)
                return result

On Thu, Feb 26, 2009 at 3:58 PM, Asheesh Laroia <asheesh at asheesh.org> wrote:

> On Wed, 25 Feb 2009, Charles Merriam wrote:
>  In the spirit of just in time research for the newbie nugget tomorrow:
>> What decorators do most people actually use?
> I *frequently* use a @trace decorator. It reminds me of the lovely days of
> the TRACE macro in Common Lisp. I typically write my own, but given a good
> standard-ish one I could use that.
> -- Asheesh.
> --
> Of course you have a purpose -- to find a purpose.
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20090226/3625669f/attachment.htm>

More information about the Baypiggies mailing list