Python: Redefining function from within the function
<p>I have some expensive function f(x) that I want to only calculate once, but is called rather frequently. In essence, the first time the function is called, it should compute a whole bunch of values for a range of x since it will be integrated over anyway and then interpolate that one with splines, and cache the coefficients somehow, possibly in a file for further use.</p>

<p>My idea was to do something like the following, since it would be pretty easy to implement. First time the function is called, it does something, then redefines itself, then does something else from then on. However, it does not work as expected and might in general be bad practice.</p>

<pre><code>def f():
    def g():
        print(2)
    print(1)
    f = g
f()
f()
</code></pre>

<p>Expected output:</p>

<pre><code>1
2
</code></pre>

<p>Actual output:</p>

<pre><code>1
1
</code></pre>

<p>Defining g() outside of f() does not help. Why does this not work? Other than that, the only solution I can think of right now is to use some global variable. Or does it make sense to somehow write a class for this?</p>
