Lesser evil hack? (static data)

Fred L. Drake fdrake at cnri.reston.va.us
Thu May 27 13:31:56 EDT 1999


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




More information about the Python-list mailing list