PyViz Comms
pyviz-comms is a Python library that provides a simple bidirectional communication architecture between Python and JavaScript, primarily for use within Jupyter environments (Classic Notebook and JupyterLab). It acts as a low-level building block for the HoloViz ecosystem, enabling interactive content rendering. The library is currently at version 3.0.6 and aligns its major releases with JupyterLab versions to ensure compatibility.
Warnings
- breaking For JupyterLab versions older than 3.0, the `@pyviz/jupyterlab_pyviz` extension needed to be installed manually using `jupyter labextension install @pyviz/jupyterlab_pyviz`. `pyviz-comms` version 3.x is specifically designed for JupyterLab 3.x and 4.x, where the extension is automatically bundled with the Python package.
- gotcha The project was formerly known as 'PyViz', which can cause confusion with the broader 'PyViz.org' community project that catalogs all Python visualization tools. `pyviz-comms` is now firmly part of the 'HoloViz' ecosystem.
- gotcha pyviz-comms provides a low-level communication primitive. Most users of the HoloViz ecosystem will interact with this functionality indirectly through higher-level libraries like Panel, HoloViews, or Bokeh, rather than directly using `pyviz_comms.Comm`. Direct usage often requires detailed knowledge of both Python and JavaScript comms.
Install
-
pip install pyviz-comms
Imports
- Comm
from pyviz_comms import Comm
- IPyComm
from ipykernel.comm import Comm as IPyComm
Quickstart
from pyviz_comms import Comm
from IPython.display import display, Javascript
def python_message_handler(msg):
print(f"Python received: {msg['content']['data']}")
# Create a new comm target
comm_id = 'my_pyviz_comm_example'
comm = Comm(target_name=comm_id, data={})
comm.on_msg(python_message_handler)
# Send a message from Python to the frontend
comm.send(data={'status': 'hello from python!'})
# To make this truly bidirectional, a JavaScript counterpart is needed in the Jupyter frontend.
# Run the following JavaScript in a separate Jupyter cell:
#
# %%javascript
# if (window.PyViz == undefined) { window.PyViz = {}; }
# if (window.PyViz.comms == undefined) { window.PyViz.comms = {}; }
#
# Jupyter.notebook.kernel.comm_manager.register_target('my_pyviz_comm_example', function(comm) {
# window.PyViz.comms[comm.comm_id] = comm;
# comm.on_msg(function(msg) {
# console.log("JS received:", msg.content.data);
# comm.send({'response': 'hello from JS!'});
# });
# comm.send({'ready': true});
# console.log("JS comm 'my_pyviz_comm_example' registered and ready.");
# });
# After running the JS, you could send another message from Python:
# comm.send(data={'action': 'update_chart'})