nbval
nbval copied to clipboard
Instrospection: get source of the cell from the cell ?
When executing a notebook with nbval, get_ipython().history_manager.input_hist_raw (mentioned by @takluyver in https://github.com/jupyter/notebook/issues/3101#issuecomment-348549723) does not work for recent versions of nbval, so it is not possible to get the source of a cell from a cell.
I used this feature in https://transonic.readthedocs.io and I test it with nbval~=0.9.6.
Is it possible to get the cell input in Python from the cell with recent version of nbval ?
Probably from #190, making nbval not store every cell it runs into your IPython history database.
I think this is another option that probably still works:
import sys, linecache
linecache.getlines(sys._getframe().f_code.co_filename)
But this is all a bunch of implementation details, so don't be too surprised if that one day stops working as well. If you want a stable API to get the code cell currently running, that would be up to IPython or ipykernel - but I think it's a pretty niche request.
(Oh, and in case it's not obvious, the sys._getframe() thing needs to be directly in a code cell, not wrapped in a function. You could walk the stack from inside a function to get back to the code cell, if you need to, but it's going to get fiddly.)