faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 5 people (60%) answered Yes
Recently 2 of 4 people (50%) answered Yes

Entry

Memoized function (was: Lesser evil hack? (static data))

Jul 5th, 2000 10:00
Nathan Wallace, Hans Nowak, Snippet 160, Fred L. Drake


"""
Packages: oop;miscellaneous
"""
"""
> I've followed the "how to imitate a C static variable" thread with
> some interest, and now feel compelled to float my attempt at it for
I've missed the whole thing.  Whew!
This should do what you want; there's no need for C's "static"
variables.  There's no support for keyword parameters to the function; 
it could be done but would be more expensive and would rely more on
the caller to always use the same syntax.  This ensures that only
positional parameter syntax is used.
The same memo() function can be used for any function for which this 
is useful, and can be tossed in a separate module.
"""
#------------------------------------------------------------------------
class MemoizedFunction:
    def __init__(self, function):
        self.function = function
        self.memo = {}
    def __call__(self, *args):
        try:
            return self.memo[args]
        except KeyError:
            # uncomputed value
            v = apply(self.function, args)
            self.memo[args] = v
            return v
        except TypeError:
            # args was not hashable; don't cache the result
            return apply(self.function, args)
def memo(function):
    return MemoizedFunction(function).__call__
# example of usage
'''
def GaussPointsAndWeights(order):
    """Return Gauss integration points (in [-1, 1]) and weights."""
    if order == 2:
        ...
    elif order == 4:
        ...
    ...                             # Create pairs (a list of tuples),
                                    # possibly at great expense.
    return pairs
GaussPointsAndWeights = memo(GaussPointsAndWeights)
'''