0

I am using the %store magic to save a variable, then I'd like to %store -r that variable in the same notebook, different execution.

In order to automate this, I'd like to do something like:

try:
    %store my_variable
except UsageError:
    %store -r my_variable

The problem is that the UsageError isn't getting caught by the try/except statement (probably due to the fact that is a line magic?) Is there a way to do this?

Context

My motivation is that my notebook has a specific cell that is executed or not depending on a flag. This cell calls a heavy function that can take hours to terminate, the result being the variable I want to store. Because I need to restart the kernel after this heavy function has finished, I then run all the previous cells to this "heavy cell" and load the result to continue the analysis.

I could of course have the magic inside the heavy cell and then just load it, but that feels manual and error-prone (could overwrite a new, unsaved result if I am careless), hence the try/except approach.

Adrian
  • 755
  • 9
  • 17
  • I think you want to persist results of heavy cell. But saving in notebook is not a good idea because notebook is just a editor and code should not dependent on it. You can save this to pickle object and read whenever it requires. – Suryaveer Singh Aug 26 '20 at 08:17
  • `%store` persists across sessions. In fact I think it pickles the variables under the hood (documentation says that the item must be pickleable). To give you an idea of the viability of persisting things using `%store`, today I realized I had a variable from 5 months ago `%store`'d hehe – Adrian Aug 26 '20 at 08:39
  • on way is to write custom handler and check if variable is there using another try cache assuming you have the variable. It will return you Name error exception – Suryaveer Singh Aug 26 '20 at 08:51

0 Answers0