memoize again

Discussion in 'Python' started by yota.news@gmail.com, Nov 21, 2009.

  1. Guest

    I spent a lot of time looking for tips on how to properly write
    cache / memoize function.
    Testing, merging and fixing contributed but half finished pieces of
    code.
    Here is the summary of what I learned through a clean example, might
    it be useful for beginners.

    #!/usr/bin/env python3.1 (should work in python 2.5)

    def dcache(function) :
    """ simple, dict based cache """
    return memoize(function, cache={})

    def ccache(cache = {}):
    """ with dict-like custom cache. Can be any class with
    at least __contains__, __setitem__ and __getitem__ methods """
    def xcache(function):
    return memoize(function, cache=cache)
    return xcache

    class memoize(object):
    def __init__(self, function, cache):
    self.function=function
    self.cache=cache

    def __get__(self, instance, cls=None):
    self.instance = instance
    return self

    def __call__(self, *args):
    if args not in self.cache:
    self.cache[args] = self.function(self.instance, *args)
    return self.cache[args]

    which can be used as this:
    - with the custom cache

    @ccache(cache=customCache())
    def compute(self, alpha, beta):
    return alpha + beta

    - or with a default dict() cache

    @dcache
    def compute(self, alpha, beta):
    return alpha + beta

    Each time compute() is called, the memoize decorator looks first into
    the cache for a value whose key is the *args tuple.

    The full content of the cache can be acessed as compute.cache.


    , Nov 21, 2009
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Chris Reedy

    How to memoize functions?

    Chris Reedy, Jun 26, 2003, in forum: Python
    Replies:
    3
    Views:
    987
    Chris Reedy
    Jun 27, 2003
  2. Replies:
    0
    Views:
    649
  3. Replies:
    2
    Views:
    763
  4. Michael Hohn
    Replies:
    3
    Views:
    1,100
    Dima Dorfman
    Oct 31, 2004
  5. Replies:
    11
    Views:
    621
    Gabriel Genellina
    Aug 19, 2006
Loading...

Share This Page