py3Dmol
py3Dmol is an IPython interface for embedding 3Dmol.js views in Jupyter notebooks. It enables dependency-free interactive molecular visualization, as a minified version of the 3Dmol.js library is included directly. It supports rendering various molecular objects and is currently at version 2.5.4, with active development under the 3Dmol.js ecosystem.
Common errors
-
blank output
cause Often caused by browser caching an older version of the 3Dmol.js JavaScript library, or incompatibility with older JupyterLab versions' stricter security policies for JavaScript injection.fixClear your browser's cache, especially for Chrome. Restart your Jupyter Notebook server. If using JupyterLab, ensure all Jupyter/widget extensions are up-to-date. -
Error: Kernel message validation error: Missing property 'metadata'
cause This error typically occurs in specific Jupyter environments (like JupyterLite) where the display message content, generated by `py3Dmol`, is not resilient to missing metadata properties expected by the kernel's message validation.fixThis issue was often addressed by updates in the Jupyter environment (e.g., JupyterLite's kernel to ensure metadata is always included in display messages). Ensure your Jupyter environment is up-to-date. If the problem persists in a custom setup, it might indicate a need to ensure metadata is present in `IPython.display.publish_display_data()` calls.
Warnings
- breaking The underlying 3Dmol.js library (version 2.0.0, released around late 2022/early 2023) introduced minor breaking changes in its `GLModel` API. Functions that previously required a viewer argument (e.g., `vibrate`) no longer do, as models now intrinsically track their viewer. This caused initial compatibility issues with py3Dmol versions.
- gotcha py3Dmol widgets are static; there is only one-way communication from Python to the viewer. While the embedded 3D viewer is interactive in the browser (e.g., rotating, zooming), any changes made directly in the viewer UI are not communicated back to the Python kernel. This means viewer state cannot be directly read or manipulated by Python after initial rendering without re-rendering.
- gotcha Users may encounter blank output in Jupyter notebooks or JupyterLab, particularly after updates or in specific browser environments (e.g., Chrome). This can be due to browser caching old JavaScript files or compatibility issues with older JupyterLab security settings.
Install
-
pip install py3Dmol
Imports
- view
import py3Dmol view = py3Dmol.view(...)
Quickstart
import py3Dmol
# Create a viewer instance and load a PDB structure by query
view = py3Dmol.view(query='pdb:1ubq')
# Set a cartoon style with spectrum coloring
view.setStyle({'cartoon':{'color':'spectrum'}})
# Zoom to fit the entire molecule
view.zoomTo()
# Display the visualization in the notebook
view