0

I'm trying to create an ipython magic somewhat akin to the %pylab, but more explicit (probably a follow-up from here ):

When run, it would ideally replace itself with a commented version + append the lines that do the imports and run the cell:

%mymagic
# some code

would turn into

# %mymagic
import numpy as np
%matplotlib qt
import matplotlib.pyplot as plt
# ..some other imports
# the same code from earlier

The thinking being that not only the magic will only do extremely explicit things - i.e. you will actually see the code that it run / it will be saved explicitly in the notebook, but also convenient as usual - just a quick few symbols for the imports (useful in consoles).

The problem for me is then running the cell after changing it (I used %load magic as an example, so I use set_next_input to change the cell). I've tried running the imports inside the magic (i.e. exactly how the %pylab did it) and then changing the cell, but that has the disadvantage of leaving the cell in the "not run" state, and does not work as well then the magic is called in the ipython console (you have to press enter to get rid of the explicit text). Also, the the same code has to be maintained twice (one for "printing", and second time - for actual import when executing the magic)

Any advice how to approach this? Thanks

0 Answers0