Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating a 'local static' variable in python

Tags:

python

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()  
like image 526
Paul Oyster Avatar asked Jan 20 '09 09:01

Paul Oyster


1 Answers

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.

like image 65
S.Lott Avatar answered Oct 08 '22 12:10

S.Lott