Interactive plots and applications in the browser from Python
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Document model and lifecycle management for Bokeh applications. The Document serves as the central container for all Bokeh models, managing their relationships, state changes, and synchronization between client and server in interactive applications.
The main Document class that serves as the container for all Bokeh models and manages their state.
class Document:
"""
Central container for all Bokeh models in an application.
The Document manages model relationships, handles state changes,
coordinates updates between client and server, and provides
the foundation for interactive Bokeh applications.
"""
def __init__(self, **kwargs):
"""
Parameters:
- title: str, document title (default: "Bokeh Application")
"""
def add_root(self, model):
"""
Add a model as a root element to the document.
Parameters:
- model: Model, Bokeh model to add as root
"""
def remove_root(self, model):
"""
Remove a root model from the document.
Parameters:
- model: Model, root model to remove
"""
@property
def roots(self):
"""List of root models in the document."""
@property
def title(self):
"""Document title string."""
@title.setter
def title(self, value):
"""Set document title."""
def clear(self):
"""Remove all models from the document."""
def add_periodic_callback(self, callback, period_milliseconds):
"""
Add a periodic callback function.
Parameters:
- callback: callable, function to call periodically
- period_milliseconds: int, callback interval in milliseconds
Returns:
Callback handle for later removal
"""
def remove_periodic_callback(self, callback_handle):
"""
Remove a periodic callback.
Parameters:
- callback_handle: handle returned by add_periodic_callback
"""
def add_timeout_callback(self, callback, timeout_milliseconds):
"""
Add a one-time timeout callback.
Parameters:
- callback: callable, function to call after timeout
- timeout_milliseconds: int, timeout in milliseconds
Returns:
Callback handle for cancellation
"""
def remove_timeout_callback(self, callback_handle):
"""
Remove a timeout callback before it executes.
Parameters:
- callback_handle: handle returned by add_timeout_callback
"""
DEFAULT_TITLE: str # "Bokeh Application"Functions and utilities for managing document context in different environments.
def curdoc():
"""
Get the current Document instance.
Returns the Document associated with the current context:
- In server applications: the session document
- In standalone scripts: a default document
- In notebooks: the notebook document
Returns:
Document: Current document instance
"""
def without_document_lock(func):
"""
Decorator to execute function without document lock.
Used when modifying documents from background threads
or async operations in server applications.
Parameters:
- func: callable, function to execute without lock
Returns:
Decorated function that executes without document lock
"""
def set_curdoc(doc):
"""
Set the current document for the execution context.
Parameters:
- doc: Document, document to set as current
"""Functions for managing models within documents and handling model relationships.
class Model:
"""Base class for all Bokeh models."""
@property
def document(self):
"""Get the document containing this model."""
def select(self, selector):
"""
Find models matching the given selector.
Parameters:
- selector: dict or type, selection criteria
Returns:
List of matching models
"""
def select_one(self, selector):
"""
Find the first model matching the given selector.
Parameters:
- selector: dict or type, selection criteria
Returns:
First matching model or None
"""
def collect_models(*models):
"""
Collect all models in a object graph.
Parameters:
- models: Model objects to traverse
Returns:
Set of all models found in the graph
"""Event system for responding to document and model changes.
class DocumentChangedEvent:
"""Base class for document change events."""
def __init__(self, document, **kwargs):
"""
Parameters:
- document: Document, document that changed
"""
class ModelChangedEvent(DocumentChangedEvent):
"""Event fired when a model property changes."""
def __init__(self, document, model, attr, old, new, **kwargs):
"""
Parameters:
- document: Document, containing document
- model: Model, model that changed
- attr: str, property name that changed
- old: any, previous property value
- new: any, new property value
"""
class RootAddedEvent(DocumentChangedEvent):
"""Event fired when a root model is added."""
def __init__(self, document, model, **kwargs):
"""
Parameters:
- document: Document, containing document
- model: Model, root model that was added
"""
class RootRemovedEvent(DocumentChangedEvent):
"""Event fired when a root model is removed."""
def __init__(self, document, model, **kwargs):
"""
Parameters:
- document: Document, containing document
- model: Model, root model that was removed
"""
class TitleChangedEvent(DocumentChangedEvent):
"""Event fired when document title changes."""
def __init__(self, document, title, **kwargs):
"""
Parameters:
- document: Document, document with changed title
- title: str, new document title
"""Functions for serializing and deserializing documents for transmission and storage.
def to_json(obj):
"""
Serialize a document or model to JSON.
Parameters:
- obj: Document or Model, object to serialize
Returns:
str: JSON representation
"""
def from_json(json_str):
"""
Deserialize a document or model from JSON.
Parameters:
- json_str: str, JSON representation
Returns:
Document or Model: Deserialized object
"""
def to_json_string(obj, **kwargs):
"""
Serialize object to JSON string with formatting options.
Parameters:
- obj: object to serialize
- indent: int, JSON indentation
- sort_keys: bool, sort object keys
Returns:
str: Formatted JSON string
"""Functions for validating document structure and model consistency.
def validate_document(doc):
"""
Validate document structure and model consistency.
Parameters:
- doc: Document, document to validate
Returns:
List of validation issues found
"""
class ValidationError(Exception):
"""Exception raised for document validation errors."""
def __init__(self, message, models=None, **kwargs):
"""
Parameters:
- message: str, error description
- models: list, models involved in the error
"""Utilities for creating document templates and reusable document patterns.
class DocumentTemplate:
"""Template for creating documents with predefined structure."""
def __init__(self, **kwargs):
"""
Parameters:
- template_vars: dict, template variables
"""
def create_document(self, **vars):
"""
Create a document from the template.
Parameters:
- vars: template variable values
Returns:
Document: Created document instance
"""
def create_document_from_template(template_path, **vars):
"""
Create document from template file.
Parameters:
- template_path: str, path to template file
- vars: template variable values
Returns:
Document: Created document
"""from bokeh.document import Document
from bokeh.plotting import figure
from bokeh.models.widgets import Button
from bokeh.layouts import column
# Create a new document
doc = Document(title="My Application")
# Create models
plot = figure(width=400, height=400)
plot.circle([1, 2, 3], [4, 5, 6], size=10)
button = Button(label="Click me")
# Add models to document
layout = column(button, plot)
doc.add_root(layout)
print(f"Document has {len(doc.roots)} root models")
print(f"Document title: {doc.title}")from bokeh.io import curdoc
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
import numpy as np
# Get current document
doc = curdoc()
# Create data source and plot
source = ColumnDataSource(data=dict(x=[1, 2, 3], y=[4, 5, 6]))
plot = figure()
plot.circle('x', 'y', source=source, size=10)
def update_data():
# Update data periodically
new_data = dict(
x=np.random.random(5),
y=np.random.random(5)
)
source.data = new_data
# Add periodic callback
callback_handle = doc.add_periodic_callback(update_data, 1000)
# Add plot to document
doc.add_root(plot)
# Later, remove callback if needed
# doc.remove_periodic_callback(callback_handle)from bokeh.document import Document
from bokeh.plotting import figure
from bokeh.models.widgets import Slider
# Create document
doc = Document()
# Create models
plot = figure()
slider = Slider(title="Value", start=0, end=100, value=50)
def on_document_change(event):
print(f"Document changed: {type(event).__name__}")
if hasattr(event, 'model'):
print(f"Model: {event.model}")
if hasattr(event, 'attr'):
print(f"Attribute: {event.attr}, New value: {event.new}")
# Listen for document changes
doc.on_change(on_document_change)
# Add models (will trigger events)
doc.add_root(plot)
doc.add_root(slider)
# Change slider value (will trigger event)
slider.value = 75from bokeh.document import Document, validate_document
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
# Create document with potential issues
doc = Document()
# Create plot with invalid data source reference
plot = figure()
# Intentionally reference non-existent data source
plot.circle('x', 'y', source="invalid_source")
doc.add_root(plot)
# Validate document
issues = validate_document(doc)
if issues:
print("Validation issues found:")
for issue in issues:
print(f"- {issue}")
else:
print("Document is valid")from bokeh.document import Document, set_curdoc, curdoc
from bokeh.plotting import figure
# Create multiple documents
doc1 = Document(title="Document 1")
doc2 = Document(title="Document 2")
# Work with first document
set_curdoc(doc1)
plot1 = figure(title="Plot 1")
plot1.line([1, 2, 3], [1, 4, 2])
curdoc().add_root(plot1)
# Switch to second document
set_curdoc(doc2)
plot2 = figure(title="Plot 2")
plot2.circle([1, 2, 3], [3, 1, 4], size=10)
curdoc().add_root(plot2)
print(f"Doc 1 title: {doc1.title}, roots: {len(doc1.roots)}")
print(f"Doc 2 title: {doc2.title}, roots: {len(doc2.roots)}")# Document-related types
DocumentLike = Union[Document, None]
ModelLike = Union[Model, str]
CallbackLike = Callable[[], None]
EventLike = Union[DocumentChangedEvent, ModelChangedEvent]
# Callback types
PeriodicCallbackHandle = Any # Handle for periodic callbacks
TimeoutCallbackHandle = Any # Handle for timeout callbacks
PeriodType = int # Milliseconds for callback periods
# Validation types
ValidationIssue = str # Validation error description
ValidationResult = List[ValidationIssue]
# Serialization types
JSONDict = Dict[str, Any] # JSON object representation
JSONString = str # JSON string representation