From: fdrake at cnri.reston.va.us (Fred L. Drake)
Date: Thu, 27 May 1999 17:31:56 GMT
Subject: Lesser evil hack? (static data)
In-Reply-To: <m33e0imvou.fsf@lomond.caber-eng.com>
References: <m33e0imvou.fsf@lomond.caber-eng.com>
Message-ID: <14157.33164.738492.657883@weyr.cnri.reston.va.us>
Content-Length: 1816
X-UID: 1787                                                

D. Michael McFarland writes:
 > 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__


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)
------------------------------------------------------------------------


  -Fred

--
Fred L. Drake, Jr.	     <fdrake at acm.org>
Corporation for National Research Initiatives




