I'm trying to figure out a couple of cell operations from python

I work on a widget that does DataFrame visualization and codegen. I want the widget to be able create a cell immediately below it, and inject then edit code in that cell.

I want to create a new cell, then get a reference to that created cell (by id or something else) then be able to edit that cell.

I have found a code snippet to edit a cell, but I don’t know how to edit a cell, or find the cell I just created.

from IPython.core.getipython import get_ipython

def create_new_cell(contents):
    shell = get_ipython()
    payload = dict(
        source='set_next_input',
        text=contents,
        replace=False,
    )
    return shell.payload_manager.write_payload(payload, single=False)

I have reviewed the docs here, and I don’t obviously see how to do this?
https://jupyter-client.readthedocs.io/en/latest/messaging.html

I looked around here, but it’s not obvious how to perform the actions I’m thinking of. The notebook has all of the cell state available to it.

Any suggestions?

Payload manager was deprecated a long time ago. It has support for replace=True but it was not updated to support concept of cell IDs which were added long after it was deprecated. You may have some luck with ipylab or modifying the notebook using shared models (see jupyter-server-ydoc in GitHub - jupyterlab/jupyter-collaboration: A Jupyter Server Extension Providing Support for Y Documents).

1 Like