Simulating a 'local static' variable in python
<p>Consider the following code:  </p>

<pre><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 = { }
</code></pre>

<p>This is the easiest way I can think of for simulating a 'local static' variable in python.<br />
What bothers me is that CalcSomething._cache is mentioned outside the function's definition, but the alternative would be something like that:  </p>

<pre><code>if not hasattr(CalcSomething, "_cache"):  
    setattr(CalcSomething, "_cache", { } )
</code></pre>

<p>inside the function's definition, which is really cumbersome.  </p>

<p>Is there a more elegant way?  </p>

<p>[EDIT]<br />
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:  </p>

<pre><code>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()
</code></pre>
