Lesser evil hack? (static data)

Jeremy Hylton jeremy at cnri.reston.va.us
Thu May 27 16:18:55 EDT 1999


I think there is a better way to associate static data with a
function.  Use a class that implements __call__.  You can call it just 
like a function, but you can also manipulate the "static" data just as 
you would any other instance variable.  There's none of the contortions
that other schemes (FAST and otherwise) that people have suggested.

class GaussPointsAndWeightsClass:
    def __init__(self):
        self.memo = {}

    def __call__(self, order):
        if self.memo.has_key(order):
            return self.memo[order]
        # do the real work
        self.memo[order] = ... # the result
        return self.memo[order]

GaussPointsAndWeights = GaussPointsAndWeightsClass()

There's no need to make this specific to Gauss's bowling score or his
weight, though.  You can just as easily have a generic class that
implements the memoization and use subclassing or delegation to attach 
the real function to it.

class Memoize:
    def __init__(self, func):
        self.memo = {}
        self.func = func

    def __call__(self, *args):
        if not self.memo.has_key(args):
            self.memo[args] = apply(self.func, args)
        return self.memo[args]

def GaussPointsAndWeightsReal(order):
    return 42

GaussPointsAndWeights = Memoize(GaussPointsAndWeightsReal)


Jeremy




More information about the Python-list mailing list