0

Let's say I have a python function, where x and y are relatively large objects (lists, NumPy matrices, etc.):

def myfun(x):
  y=some complicated function of x
  return y

If in an interactive session the user calls this as:

myfun(5)

The call is basically useless, since y 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. answer=myfun(5)? 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:

Require a parameter that stores the value, e.g.

def myfun(x,y):
  y = some complicated function of x
  return y

Or maybe:

def myfun(x):
  y = some complicated function of x
  global temp
  temp = y
  return y

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

DanB
  • 83
  • 6

1 Answers1

4

y=_

assuming you are in the interactive python console. _ is magic that holds the last "result"

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • 1
    (additionally the question does not make much sense outside of that context :P ) – Joran Beasley Sep 28 '16 at 23:39
  • 1
    And if you're using IPython, results like this are also stored in the `Out` object, so you can look at the little `Out[15]:` or `Out[42]:` label next to your output and access `Out[15]` or `Out[42]` to get at objects that have been shoved out of `_` by further outputs. – user2357112 Sep 28 '16 at 23:44
  • ahh I fiigured ipython had some extra bells and whistles :P but i dont use it enough so :P – Joran Beasley Sep 28 '16 at 23:44
  • Wow, that was a perfect and easy solution, thank you! – DanB Sep 29 '16 at 04:12