Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: use anywidget types and widget.get_state() (#3921)

Myles Scolnick50fc11f1d2cc
diff --git a/frontend/package.json b/frontend/package.json
index c95588b07d..00650ea802 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -13,6 +13,7 @@
"dist"
],
"dependencies": {
+ "@anywidget/types": "^0.2.0",
"@codemirror/autocomplete": "^6.18.4",
"@codemirror/commands": "^6.8.0",
"@codemirror/lang-markdown": "^6.3.2",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 3e7cd2cfaf..c14ee0b6a2 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -15,6 +15,9 @@ importers:
.:
dependencies:
+ '@anywidget/types':
+ specifier: ^0.2.0
+ version: 0.2.0
'@codemirror/autocomplete':
specifier: ^6.18.4
version: 6.18.6
@@ -659,6 +662,9 @@ packages:
resolution: {integrity: sha512-+562v9k4aI80m1+VuMHehNJWLOFjBnXn3tdOitzD0il5b7smkSBal4+a3oKiQTbrwMmN/TBUMDvbdoWDehgOww==}
+ '@anywidget/[email protected]':
+ resolution: {integrity: sha512-+XtK4uwxRd4JpuevUMhirrbvC0V4yCA/i0lEjhmSAtOaxiXIg/vBKzaSonDuoZ1a9LEjUXTW2+m7w+ULgsJYvg==}
+
resolution: {integrity: sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==}
engines: {node: '>=6.9.0'}
@@ -9087,6 +9093,8 @@ snapshots:
'@antfu/[email protected]': {}
+ '@anywidget/[email protected]': {}
+
dependencies:
'@babel/helper-validator-identifier': 7.25.9
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index b944f5c4b7..c8b749d6da 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -5,12 +5,11 @@ import { z } from "zod";
import type { IPluginProps } from "@/plugins/types";
import { useEffect, useMemo, useRef } from "react";
import { useAsyncData } from "@/hooks/useAsyncData";
-import { dequal } from "dequal";
import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";
import { ErrorBanner } from "../common/error-banner";
import { createPlugin } from "@/plugins/core/builder";
import { rpc } from "@/plugins/core/rpc";
-import type { AnyModel, AnyWidget, EventHandler, Experimental } from "./types";
+import type { AnyWidget, Experimental } from "@anywidget/types";
import { Logger } from "@/utils/Logger";
import {
type HTMLElementNotDerivedFromRef,
@@ -18,7 +17,7 @@ import {
} from "@/hooks/useEventListener";
import { MarimoIncomingMessageEvent } from "@/core/dom/events";
import { updateBufferPaths } from "@/utils/data-views";
-import { debounce } from "lodash-es";
+import { Model } from "./model";
interface Data {
jsUrl: string;
@@ -203,147 +202,3 @@ const LoadedSlot = ({
return <div ref={ref} />;
};
-
-export class Model<T extends Record<string, any>> implements AnyModel<T> {
- private ANY_CHANGE_EVENT = "change";
-
- constructor(
- private data: T,
- private onChange: (value: Partial<T>) => void,
- private send_to_widget: (req: { content?: any }) => Promise<
- null | undefined
- >,
- ) {}
-
- private dirtyFields = new Set<keyof T>();
-
- off(eventName?: string | null, callback?: EventHandler | null): void {
- if (!eventName) {
- this.listeners = {};
- return;
- }
-
- if (!callback) {
- this.listeners[eventName] = new Set();
- return;
- }
-
- this.listeners[eventName]?.delete(callback);
- }
-
- send(
- content: any,
- callbacks?: any,
- buffers?: ArrayBuffer[] | ArrayBufferView[],
- ): void {
- if (buffers) {
- Logger.warn("buffers not supported in marimo anywidget.send");
- }
- this.send_to_widget({ content }).then(callbacks);
- }
-
- widget_manager = new Proxy(
- {},
- {
- get() {
- throw new Error("widget_manager not supported in marimo");
- },
- set() {
- throw new Error("widget_manager not supported in marimo");
- },
- },
- );
-
- private listeners: Record<string, Set<EventHandler>> = {};
-
- get<K extends keyof T>(key: K): T[K] {
- return this.data[key];
- }
-
- set<K extends keyof T>(key: K, value: T[K]): void {
- this.data = { ...this.data, [key]: value };
- this.dirtyFields.add(key);
- this.emit(`change:${key as K & string}`, value);
- this.emitAnyChange();
- }
-
- save_changes(): void {
- if (this.dirtyFields.size === 0) {
- return;
- }
- const partialData: Partial<T> = {};
- this.dirtyFields.forEach((key) => {
- partialData[key] = this.data[key];
- });
- this.dirtyFields.clear();
- this.onChange(partialData);
- }
-
- updateAndEmitDiffs(value: T): void {
- Object.keys(value).forEach((key) => {
- const k = key as keyof T;
- if (!dequal(this.data[k], value[k])) {
- this.set(k, value[k]);
- }
- });
- }
-
- /**
- * When receiving a message from the backend.
- * We want to notify all listeners with `msg:custom`
- */
- receiveCustomMessage(message: any, buffers?: DataView[]): void {
- const response = WidgetMessageSchema.safeParse(message);
- if (response.success) {
- const data = response.data;
- switch (data.method) {
- case "update":
- this.updateAndEmitDiffs(data.state as T);
- break;
- case "custom":
- this.listeners["msg:custom"]?.forEach((cb) =>
- cb(data.content, buffers),
- );
- break;
- }
- } else {
- Logger.error("Failed to parse message", response.error);
- Logger.error("Message", message);
- }
- }
-
- on(eventName: string, callback: EventHandler): void {
- if (!this.listeners[eventName]) {
- this.listeners[eventName] = new Set();
- }
- this.listeners[eventName].add(callback);
- }
-
- private emit<K extends keyof T>(event: `change:${K & string}`, value: T[K]) {
- if (!this.listeners[event]) {
- return;
- }
- this.listeners[event].forEach((cb) => cb(value));
- }
-
- // Debounce 0 to send off one request in a single frame
- private emitAnyChange = debounce(() => {
- this.listeners[this.ANY_CHANGE_EVENT]?.forEach((cb) => cb());
- }, 0);
-}
-
-const WidgetMessageSchema = z.union([
- z.object({
- method: z.literal("update"),
- state: z.record(z.any()),
- }),
- z.object({
- method: z.literal("custom"),
- content: z.any(),
- }),
- z.object({
- method: z.literal("echo_update"),
- buffer_paths: z.array(z.array(z.union([z.string(), z.number()]))),
- state: z.record(z.any()),
- }),
-]);
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts
index 03e8fba0b0..67ed37e97f 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts
+++ b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { Model } from "../AnyWidgetPlugin";
+import { Model } from "../model";
import { vi, describe, it, expect, beforeEach } from "vitest";
describe("Model", () => {
@@ -124,12 +124,7 @@ describe("Model", () => {
describe("widget_manager", () => {
it("should throw error when accessing widget_manager", () => {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- expect(() => (model.widget_manager as any).foo).toThrow(
- "widget_manager not supported in marimo",
- );
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- expect(() => ((model.widget_manager as any).foo = "bar")).toThrow(
+ expect(() => model.widget_manager.get_model("foo")).toThrow(
"widget_manager not supported in marimo",
);
});
diff --git a/frontend/src/plugins/impl/anywidget/model.ts b/frontend/src/plugins/impl/anywidget/model.ts
new file mode 100644
index 0000000000..663ba3a742
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/model.ts
@@ -0,0 +1,146 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+import { Logger } from "@/utils/Logger";
+import type { AnyModel } from "@anywidget/types";
+import { dequal } from "dequal";
+import { debounce } from "lodash-es";
+import { z } from "zod";
+
+export type EventHandler = (...args: any[]) => void;
+
+export class Model<T extends Record<string, any>> implements AnyModel<T> {
+ private ANY_CHANGE_EVENT = "change";
+
+ constructor(
+ private data: T,
+ private onChange: (value: Partial<T>) => void,
+ private sendToWidget: (req: { content?: any }) => Promise<null | undefined>,
+ ) {}
+
+ private dirtyFields = new Set<keyof T>();
+ private listeners: Record<string, Set<EventHandler>> = {};
+
+ off(eventName?: string | null, callback?: EventHandler | null): void {
+ if (!eventName) {
+ this.listeners = {};
+ return;
+ }
+
+ if (!callback) {
+ this.listeners[eventName] = new Set();
+ return;
+ }
+
+ this.listeners[eventName]?.delete(callback);
+ }
+
+ send(
+ content: any,
+ callbacks?: any,
+ buffers?: ArrayBuffer[] | ArrayBufferView[],
+ ): void {
+ if (buffers) {
+ Logger.warn("buffers not supported in marimo anywidget.send");
+ }
+ this.sendToWidget({ content }).then(callbacks);
+ }
+
+ widget_manager = {
+ get_model<TT extends Record<string, any>>(
+ _model_id: string,
+ ): Promise<AnyModel<TT>> {
+ throw new Error("widget_manager not supported in marimo");
+ },
+ };
+
+ get<K extends keyof T>(key: K): T[K] {
+ return this.data[key];
+ }
+
+ set<K extends keyof T>(key: K, value: T[K]): void {
+ this.data = { ...this.data, [key]: value };
+ this.dirtyFields.add(key);
+ this.emit(`change:${key as K & string}`, value);
+ this.emitAnyChange();
+ }
+
+ save_changes(): void {
+ if (this.dirtyFields.size === 0) {
+ return;
+ }
+ const partialData: Partial<T> = {};
+ this.dirtyFields.forEach((key) => {
+ partialData[key] = this.data[key];
+ });
+ this.dirtyFields.clear();
+ this.onChange(partialData);
+ }
+
+ updateAndEmitDiffs(value: T): void {
+ Object.keys(value).forEach((key) => {
+ const k = key as keyof T;
+ if (!dequal(this.data[k], value[k])) {
+ this.set(k, value[k]);
+ }
+ });
+ }
+
+ /**
+ * When receiving a message from the backend.
+ * We want to notify all listeners with `msg:custom`
+ */
+ receiveCustomMessage(message: any, buffers?: DataView[]): void {
+ const response = WidgetMessageSchema.safeParse(message);
+ if (response.success) {
+ const data = response.data;
+ switch (data.method) {
+ case "update":
+ this.updateAndEmitDiffs(data.state as T);
+ break;
+ case "custom":
+ this.listeners["msg:custom"]?.forEach((cb) =>
+ cb(data.content, buffers),
+ );
+ break;
+ }
+ } else {
+ Logger.error("Failed to parse message", response.error);
+ Logger.error("Message", message);
+ }
+ }
+
+ on(eventName: string, callback: EventHandler): void {
+ if (!this.listeners[eventName]) {
+ this.listeners[eventName] = new Set();
+ }
+ this.listeners[eventName].add(callback);
+ }
+
+ private emit<K extends keyof T>(event: `change:${K & string}`, value: T[K]) {
+ if (!this.listeners[event]) {
+ return;
+ }
+ this.listeners[event].forEach((cb) => cb(value));
+ }
+
+ // Debounce 0 to send off one request in a single frame
+ private emitAnyChange = debounce(() => {
+ this.listeners[this.ANY_CHANGE_EVENT]?.forEach((cb) => cb());
+ }, 0);
+}
+
+const WidgetMessageSchema = z.union([
+ z.object({
+ method: z.literal("update"),
+ state: z.record(z.any()),
+ }),
+ z.object({
+ method: z.literal("custom"),
+ content: z.any(),
+ }),
+ z.object({
+ method: z.literal("echo_update"),
+ buffer_paths: z.array(z.array(z.union([z.string(), z.number()]))),
+ state: z.record(z.any()),
+ }),
+]);
diff --git a/frontend/src/plugins/impl/anywidget/types.ts b/frontend/src/plugins/impl/anywidget/types.ts
deleted file mode 100644
index 2411ebf8d3..0000000000
--- a/frontend/src/plugins/impl/anywidget/types.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-/* Copyright 2024 Marimo. All rights reserved. */
-/* eslint-disable @typescript-eslint/no-invalid-void-type */
-/* eslint-disable @typescript-eslint/no-explicit-any */
-
-// Copied from https://github.com/manzt/anywidget/blob/main/packages/types/index.ts
-// with slight modifications
-// - removed widget_manager
-// We copy this for now since `@anywidget/types` pulls in jquery and backbone, which we don't need
-
-type Awaitable<T> = T | Promise<T>;
-export type EventHandler = (...args: any[]) => void;
-type ObjectHash = Record<string, any>;
-export type ChangeEventHandler<Payload> = (_: unknown, value: Payload) => void;
-type LiteralUnion<T, U = string> = T | (U & {});
-
-export interface AnyModel<T extends ObjectHash = ObjectHash> {
- get<K extends keyof T>(key: K): T[K];
- set<K extends keyof T>(key: K, value: T[K]): void;
- off<K extends keyof T>(
- eventName?: LiteralUnion<`change:${K & string}` | "msg:custom"> | null,
- callback?: EventHandler | null,
- ): void;
- on(
- eventName: "msg:custom",
- callback: (msg: any, buffers: DataView[]) => void,
- ): void;
- on<K extends `change:${keyof T & string}`>(
- eventName: K,
- callback: K extends `change:${infer Key}`
- ? ChangeEventHandler<T[Key]>
- : never,
- ): void;
- on(eventName: string, callback: EventHandler): void;
- save_changes(): void;
- send(
- content: any,
- callbacks?: any,
- buffers?: ArrayBuffer[] | ArrayBufferView[],
- ): void;
- widget_manager: {};
-}
-
-export interface Experimental {
- invoke: <T>(
- name: string,
- msg?: any,
- options?: {
- buffers?: DataView[];
- signal?: AbortSignal;
- },
- ) => Promise<[T, DataView[]]>;
-}
-export interface RenderProps<T extends ObjectHash = ObjectHash> {
- model: AnyModel<T>;
- el: HTMLElement;
- experimental: Experimental;
-}
-export type Render<T extends ObjectHash = ObjectHash> = (
- props: RenderProps<T>,
-) => Awaitable<void | (() => Awaitable<void>)>;
-export interface InitializeProps<T extends ObjectHash = ObjectHash> {
- model: AnyModel<T>;
- experimental: Experimental;
-}
-
-export type Initialize<T extends ObjectHash = ObjectHash> = (
- props: InitializeProps<T>,
-) => Awaitable<void | (() => Awaitable<void>)>;
-interface WidgetDef<T extends ObjectHash = ObjectHash> {
- initialize?: Initialize<T>;
- render?: Render<T>;
-}
-export type AnyWidget<T extends ObjectHash = ObjectHash> =
- | WidgetDef<T>
- | (() => Awaitable<WidgetDef<T>>);
diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.py
index df866bc3e2..15c8f9fa1c 100644
--- a/marimo/_plugins/ui/_impl/from_anywidget.py
+++ b/marimo/_plugins/ui/_impl/from_anywidget.py
@@ -9,7 +9,6 @@ from typing import TYPE_CHECKING, Any, Optional
import marimo._output.data.data as mo_data
from marimo import _loggers
from marimo._output.rich_help import mddoc
-from marimo._plugins.core.json_encoder import WebComponentEncoder
from marimo._plugins.ui._core.ui_element import InitializationArgs, UIElement
from marimo._plugins.ui._impl.comm import MarimoComm
from marimo._runtime.functions import Function
@@ -80,8 +79,15 @@ class anywidget(UIElement[T, T]):
# This gets set to True in super().__init__()
self._initialized = False
- # Get all the traits of the widget
- args: T = widget.trait_values()
+ import ipywidgets # type: ignore
+
+ _remove_buffers = ipywidgets.widgets.widget._remove_buffers # type: ignore
+
+ # Get state with custom serializers properly applied
+ state = widget.get_state()
+ _state_no_buffers, buffer_paths, buffers = _remove_buffers(state) # type: ignore
+
+ # Remove widget-specific system traits not needed for the frontend
ignored_traits = [
"comm",
"layout",
@@ -104,30 +110,16 @@ class anywidget(UIElement[T, T]):
"_view_module_version",
"_view_name",
]
- # Remove ignored traits
- for trait_name in ignored_traits:
- args.pop(trait_name, None)
- # Keep only classes that are json serialize-able
- json_args: T = {}
- for k, v in args.items():
- try:
- # Try to see if it is json-serializable
- WebComponentEncoder.json_dumps(v)
- # Just add the plain value, it will be json-serialized later
- json_args[k] = v
- except TypeError:
- pass
- except ValueError:
- # Handle circular dependencies
- pass
+ # Filter out system traits from the serialized state
+ # This should include the binary data,
+ # see marimo/_smoke_tests/issues/2366-anywidget-binary.py
+ json_args: T = {
+ k: v for k, v in state.items() if k not in ignored_traits
+ }
js: str = widget._esm if hasattr(widget, "_esm") else "" # type: ignore [unused-ignore] # noqa: E501
css: str = widget._css if hasattr(widget, "_css") else "" # type: ignore [unused-ignore] # noqa: E501
- import ipywidgets # type: ignore
-
- _remove_buffers = ipywidgets.widgets.widget._remove_buffers # type: ignore
- _state, buffer_paths, buffers = _remove_buffers(widget.get_state()) # type: ignore
def on_change(change: T) -> None:
_put_buffers = ipywidgets.widgets.widget._put_buffers # type: ignore
@@ -180,6 +172,10 @@ class anywidget(UIElement[T, T]):
merged = {**self._prev_state, **value}
self._prev_state = merged
return merged
+
+ LOGGER.warning(
+ f"Expected anywidget value to be a dict, got {type(value)}"
+ )
self._prev_state = value
return value
diff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.py
index f0f4352a8a..ee6e7f5801 100644
--- a/tests/_plugins/ui/_impl/test_anywidget.py
+++ b/tests/_plugins/ui/_impl/test_anywidget.py
@@ -225,12 +225,25 @@ x = as_marimo_element.count
class NonSerializableWidget(_anywidget.AnyWidget):
_esm = ""
serializable = traitlets.Int(1).tag(sync=True)
- non_serializable = traitlets.Instance(object)
+ non_serializable = traitlets.Instance(object, sync=True)
wrapped = anywidget(NonSerializableWidget())
- assert "serializable" in wrapped._initial_value
- assert wrapped._initial_value["non_serializable"] is None
+ assert wrapped._initial_value == {
+ "serializable": 1,
+ "non_serializable": None,
+ }
+ @staticmethod
+ async def test_skips_non_sync_traits() -> None:
+ class NonSyncWidget(_anywidget.AnyWidget):
+ _esm = ""
+ non_sync = traitlets.Int(1)
+ sync = traitlets.Int(2).tag(sync=True)
+
+ wrapped = anywidget(NonSyncWidget())
+ assert wrapped._initial_value == {"sync": 2}
+
+ @staticmethod
@staticmethod
async def test_frontend_changes(
k: Kernel, exec_req: ExecReqProvider