IPython cell_magic access to cell id

122 Views Asked by At

We implemented an IPython extension using the @magics_class (and @line_magic and @cell_magic) annotations. It is working quite well for the most part, with one important limitation. @cell_magic only gets the cell contents as an argument, but we need a way of identifying the actual cell somehow.

I suspect IPython would internally have an identifier for each cell, but this is not passed into the cell magic as far as I can tell.

The reason for needing this is because we want different functionality depending on whether the call is the result of an edit or whether it's a new cell.

Thanks!

1

There are 1 best solutions below

0
On

Unfortunately, the cell ID is not being passed to your magic function/class and no API could obtain it directly. However, you can use an event listener to get the cell ID that will be executed before calling your magic function/class.

from IPython.core.magic import register_cell_magic
from IPython import get_ipython
cell_id = None

def pre_run_cell(info):
    global cell_id
    cell_id = info.cell_id

get_ipython().events.register('pre_run_cell', pre_run_cell)

@register_cell_magic
def testmagic(line, cell):
    global cell_id
    print(cell_id)

And then run the cell magic with

%%testmagic

random-content

It will print the cell id. You could validate the result by checking the content of .ipynb.