Consider the following code:
def CalcSomething(a): if CalcSomething._cache.has_key(a): return CalcSomething._cache[a] CalcSomething._cache[a] = ReallyCalc(a) return CalcSomething._cache[a] CalcSomething._cache = { }
This is the easiest way I can think of for simulating a 'local static' variable in python.
What bothers me is that CalcSomething._cache is mentioned outside the function's definition, but the alternative would be something like that:
if not hasattr(CalcSomething, "_cache"): setattr(CalcSomething, "_cache", { } )
inside the function's definition, which is really cumbersome.
Is there a more elegant way?
[EDIT]
Just to clarify, this question is not about local function caches, as the example above might suggest. Here is another short example where a 'static local' might be handy:
def ParseString(s): return ParseString._parser.parse(s) # Create a Parser object once, which will be used for all parsings. # Assuming a Parser object is heave on resources, for the sake of this example. ParseString._parser = Parser()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With