Store or read stored variable in jupyter notebooks, using try/except

1.3k Views Asked by At

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.

0

There are 0 best solutions below