How can I evaluate Python code in the document context from JavaScript in JupyterLab?

Viewed 260

With Jupyter Notebooks, I could have a cell

%%javascript IPython.notebook.kernel.execute('x = 42')

Then, elsewhere in the document a Python code cell with x would show it bound to 42 as expected.

I'm trying to produce something similar with JupyterLab. I understand I'm supposed to write a plugin rather than using ad-hoc JS, and that's fine, but I'm not finding an interface to the kernel similar to the global IPython from notebooks:

import { JupyerLab, JupyterLabPlugin } from '@jupyterlab/application';
const extension: JupyterLabPlugin<void> = {
    // ...
    requires: [],
    activate: (app: JupyterLab) => {
        // can I get to Python evaluation through app?
        // by adding another class to `requires` above?
    }
}
export default extension;
1 Answers

Here's a hacky attempt that "works". Could still use advice if anyone knows where there is a public promise for the kernel being ready, how to avoid the intermediate class, or any other general improvements:

import { JupyterLab, JupyterLabPlugin } from '@jupyterlab/application';
import { DocumentRegistry } from '@jupyterlab/docregistry';
import { INotebookModel, NotebookPanel } from '@jupyterlab/notebook';
import { IDisposable, DisposableDelegate } from '@phosphor/disposable';

declare global {
    interface Window {
        'execPython': {
            'readyState': string,
            'exec': (code: string) => any,
            'ready': Promise<void>
        } | null
    }
}

class ExecWidgetExtension implements DocumentRegistry.IWidgetExtension<NotebookPanel, INotebookModel> {
    createNew(nb: NotebookPanel, context: DocumentRegistry.IContext<INotebookModel>): IDisposable {
        if (window.execPython) {
            return;
        }
        window.execPython = {
            'readyState': 'waiting',
            'exec': null,
            'ready': new Promise((resolve) => {
                const wait = setInterval(() => {
                    if (!context.session.kernel || window.execPython.readyState === 'ready') {
                        return;
                    }
                    clearInterval(wait);
                    window.execPython.readyState = 'ready';
                    window.execPython.exec = (code: string) =>
                        context.session.kernel.requestExecute({ code }, true);
                    resolve();
                }, 50);
            })
        };
        // Usage elsewhere: execPython.ready.then(() => execPython.exec('x = 42').done.then(console.log, console.error))

        return new DisposableDelegate(() => {});
    }
}

const extension: JupyterLabPlugin<void> = {
    'id': 'jupyterlab_foo',
    'autoStart': true,
    'activate': (app: JupyterLab) => {
        app.docRegistry.addWidgetExtension('Notebook', new ExecWidgetExtension())
    }
};
export default extension;
Related