PyViz Comms

3.0.6 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to establish a basic bidirectional communication channel using `pyviz_comms.Comm` within a Jupyter environment. It sets up a Python-side message handler and sends an initial message. For full interactivity, a corresponding JavaScript snippet must be executed in a Jupyter frontend cell to register the client-side comm and handle messages from Python, as well as send messages back. This example illustrates the low-level nature of `pyviz-comms`; higher-level libraries like Panel abstract much of this complexity.

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'})

view raw JSON →