Skip to main content

Read browser results

NotebookView.state reports browser work as one consistent, read-only snapshot.

import observablejs as obs

notebook = obs.Notebook(
obs.ojs(
'viewof gain = Inputs.range([0, 12], {value: 5, step: 1, label: "Gain"})',
key="gain_control",
),
obs.js("const doubled = gain * 2;", key="doubled", display=False),
obs.js(
'html`<p>Gain is <strong>${gain}</strong>. Doubled is <strong>${doubled}</strong>.</p>`',
key="readout",
),
)

view = notebook.view()
view

Read a result after the latest input revision settles. In marimo, run this in a separate cell. view.value subscribes that cell to widget updates. In Jupyter, omit that line and run the reading cell after the view renders:

view.value # marimo subscription
state = view.state

if state.errors:
print(state.errors)
elif (
not state.pending
and state.input_revision is not None
and state.settled_revision == state.input_revision
):
doubled = state.result("doubled")
if doubled.status == "success":
print(doubled.values["doubled"])
else:
print(doubled.errors)

The initial result is 10. Values use the names defined in JavaScript source. The "doubled" cell is included in notebook.view() even though display=False hides its output. A keyed expression cell captures its value under the cell key. Rendered elements become summaries in Python. Define a named variable for data that Python needs to consume.

Each CellResult has a status, revision, read-only values, and structured errors. A failed output reports its error phase and optional variable name. A multi-output cell may contain successful values beside errors.

React to state changes

Traitlets, the Python library for observable attributes, lets callbacks observe the public state trait:

def on_state(change):
state = change["new"]
if not state.pending:
print(state.results)

view.observe(on_state, names="state")

Release a callback when its consumer closes:

view.unobserve(on_state, names="state")

State belongs to the view whose runtime produced it. A focused view reports its selected result while hidden dependencies still evaluate:

gain_view = notebook.view("gain_control")

gain_view.state.result("doubled") raises KeyError because that cell is outside the selection. Select every cell whose values the consumer needs. View setup failures appear in state.errors, while evaluation failures appear in each selected result's errors.

See View state and graph for revision, status, error, and value conversion contracts.