title: Python: cache a local function variable for subsequent calls
body: <p>In C/C++, a function can declare a local variable as <code>static</code>. When doing so, the value remains in memory and is available to subsequent calls to the function (this variable is no longer local, but that's besides the point).</p>
  <p>Is there a way to do something similar in Python, <strong>without</strong> having to declare any global variable outside of the function?</p>
  <p>Use case: a function that (among other things) uses a regex to extract a value from an input string. I want to pre-compile the pattern (<code>re.compile()</code>), without having to declare the variable outside of the function scope.</p>
  <p>I can inject a variable directly into <code>globals()</code>:</p>
  <pre class="lang-py prettyprint-override"><code>globals()['my_pattern'] = re.compile(...)
  </code></pre>
  <p>But it doesn't look like a good idea.</p>