Simulating a ‘local static’ variable in python

Turn it into a callable object (since that’s what it really is.)

class CalcSomething(object):
    def __init__(self):
        self._cache = {}
    def __call__(self, a):
        if a not in self._cache: 
            self._cache[a] = self.reallyCalc(a)
        return self._cache[a]
    def reallyCalc(self, a):
        return # a real answer
calcSomething = CalcSomething()

Now you can use calcSomething as if it were a function. But it remains tidy and self-contained.

Leave a Comment