How to save value returned from python function if call does not capture return
<p>Let's say I have a python function, where <code>x</code> and <code>y</code> are relatively large objects (lists, NumPy matrices, etc.):</p>

<pre><code>def myfun(x):
  y=some complicated function of x
  return y
</code></pre>

<p>If in an interactive session the user calls this as: </p>

<pre><code>myfun(5)
</code></pre>

<p>The call is basically useless, since <code>y</code> is lost. Let's also suppose the function takes a while to run. Is there a way to retrieve the answer, so the user doesn't have to re-run, i.e. <code>answer=myfun(5)</code>? Alternatively, what is a good (pythonic) way to write the function to make it 'fool-proof' for this scenario? Some not-so-great options are:</p>

<p>Require a parameter that stores the value, e.g.</p>

<pre><code>def myfun(x,y):
  y = some complicated function of x
  return y
</code></pre>

<p>Or maybe:</p>

<pre><code>def myfun(x):
  y = some complicated function of x
  global temp
  temp = y
  return y
</code></pre>

<p>In the latter case, if a user then mistakenly called <code>myfun(5)</code>, there's the option of <code>y=temp</code> to get the answer back.. but using <code>global</code> just seems wrong.</p>

<p><code>y=_</code></p>

<p>assuming you are in the interactive python console. <code>_</code> is magic that holds the last "result"</p>

python