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.

fix: linting in PanelPlugin (#2720)

Myles Scolnick31c7cd36b7b4
diff --git a/frontend/src/plugins/impl/panel/PanelPlugin.tsx b/frontend/src/plugins/impl/panel/PanelPlugin.tsx
index 32c0f34f69..623f2c2e40 100644
--- a/frontend/src/plugins/impl/panel/PanelPlugin.tsx
+++ b/frontend/src/plugins/impl/panel/PanelPlugin.tsx
@@ -11,8 +11,8 @@ import { MarimoIncomingMessageEvent } from "@/core/dom/events";
interface Data {
extension: string | null;
- docs_json: any;
- render_json: any;
+ docs_json: Record<string, any>;
+ render_json: Record<string, any>;
}
type T = Record<string, any>;
@@ -24,12 +24,16 @@ type PluginFunctions = {
>;
};
+declare global {
+ const Bokeh: any;
+}
+
export const PanelPlugin = createPlugin<T>("marimo-panel")
.withData(
z.object({
extension: z.string().nullable(),
- docs_json: z.any(),
- render_json: z.any(),
+ docs_json: z.record(z.any()),
+ render_json: z.record(z.any()),
}),
)
.withFunctions<PluginFunctions>({
@@ -54,6 +58,9 @@ function isPlainObject<T>(obj: unknown): obj is { [key: string]: T } {
);
}
+function isBuffer(obj: unknown): obj is { buffer: ArrayBuffer } {
+ return typeof obj === "object" && obj !== null && "to_base64" in obj;
+}
function extract_buffers(value: unknown, buffers: ArrayBuffer[]): any {
if (Array.isArray(value)) {
for (const val of value) {
@@ -64,7 +71,7 @@ function extract_buffers(value: unknown, buffers: ArrayBuffer[]): any {
const v = value.get(key);
extract_buffers(v, buffers);
}
- } else if (value.to_base64 !== undefined) {
+ } else if (isBuffer(value)) {
const { buffer } = value;
const id = buffers.length;
buffers.push(buffer);
@@ -91,7 +98,7 @@ const PanelSlot = (props: Props) => {
const [loaded, setLoaded] = useState<boolean>(false);
const [rendered, setRendered] = useState<string | null>(null);
- const event_buffer = [];
+ const event_buffer: any[] = [];
let timeout = Date.now();
const process_events = () => {
@@ -110,7 +117,7 @@ const PanelSlot = (props: Props) => {
return;
}
let script: HTMLScriptElement;
- if (extension.length > 0) {
+ if (extension != null && extension.length > 0) {
script = document.createElement("script");
script.innerHTML = extension;
document.head.append(script);
@@ -126,16 +133,20 @@ const PanelSlot = (props: Props) => {
return () => {
clearInterval(checkBokeh);
};
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [extension]);
// Listen to incoming messages
useEventListener(host, MarimoIncomingMessageEvent.TYPE, (e) => {
- const doc_id = Object.keys(docs_json)[0];
- const metadata = e.detail.metadata;
+ // const doc_id = Object.keys(docs_json)[0];
+ // const metadata = e.detail.metadata;
const buffers = e.detail.buffers;
- const content = e.detail.message.content;
- if (content.type === "ACK") {
- if (event_buffer.length) {
+ if (e.detail.message == null) {
+ return;
+ }
+ const message = MessageSchema.parse(e.detail.message);
+ if (message.type === "ACK") {
+ if (event_buffer.length > 0) {
process_events();
timeout = Date.now();
} else {
@@ -143,6 +154,7 @@ const PanelSlot = (props: Props) => {
}
return;
}
+ const content = message.content;
if (content.length > 0) {
receiver.current.consume(content);
} else if (buffers !== undefined && buffers.length > 0) {
@@ -153,7 +165,7 @@ const PanelSlot = (props: Props) => {
const comm_msg = receiver.current.message;
if (comm_msg != null && Object.keys(comm_msg.content).length > 0) {
if (comm_msg.content.events !== undefined) {
- comm_msg.content.events = comm_msg.content.events.filter((e) =>
+ comm_msg.content.events = comm_msg.content.events.filter((e: any) =>
doc.current._all_models.has(e.model.id),
);
}
@@ -168,22 +180,25 @@ const PanelSlot = (props: Props) => {
}
event_buffer.length = 0;
- const sendEvent = (event) => {
+ const sendEvent = (event: any) => {
event_buffer.push(event);
if (!blocked.current || Date.now() > timeout) {
setTimeout(() => process_events(), 50);
blocked.current = true;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
timeout = Date.now() + 5000;
}
};
const embedItems = async () => {
const render_item = { ...render_json };
- const roots = {};
+ const roots: Record<string, HTMLElement | null> = {};
for (const model_id of Object.keys(render_json.roots)) {
const root_id = render_json.roots[model_id];
- const el = ref.current.querySelector(`#${root_id}`);
- roots[model_id] = el;
+ if (ref.current) {
+ const el = ref.current.querySelector(`#${root_id}`);
+ roots[model_id] = el as HTMLElement | null;
+ }
}
render_item.roots = roots;
const model_id = Object.keys(roots)[0];
@@ -209,3 +224,14 @@ const PanelSlot = (props: Props) => {
</div>
);
};
+
+const MessageSchema = z.union([
+ z.object({
+ type: z.literal("ACK"),
+ content: z.any(),
+ }),
+ z.object({
+ type: z.string().optional(),
+ content: z.any(),
+ }),
+]);
diff --git a/marimo/_output/formatters/panel_formatters.py b/marimo/_output/formatters/panel_formatters.py
index 95f54a6d4f..7588a985c3 100644
--- a/marimo/_output/formatters/panel_formatters.py
+++ b/marimo/_output/formatters/panel_formatters.py
@@ -14,8 +14,8 @@ class PanelFormatter(FormatterFactory):
return "panel"
def register(self) -> None:
- import panel # type: ignore [import-not-found]
- import param
+ import panel # type: ignore
+ import param # type: ignore
from marimo._output import formatting
diff --git a/marimo/_plugins/ui/_impl/from_panel.py b/marimo/_plugins/ui/_impl/from_panel.py
index 5b65ededec..8d06bd36e3 100644
--- a/marimo/_plugins/ui/_impl/from_panel.py
+++ b/marimo/_plugins/ui/_impl/from_panel.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import sys
from dataclasses import dataclass
from functools import partial
-from typing import Any, Dict, ForwardRef, Optional, Tuple
+from typing import Any, Dict, Optional, Tuple
from marimo import _loggers
from marimo._output.rich_help import mddoc
@@ -32,21 +32,21 @@ T = Dict[str, Any]
@dataclass
class SendToWidgetArgs:
message: Any
- buffers: Optional[Any] = None
+ buffers: Optional[Dict[int, Any]] = None
-def _get_comm_class() -> ForwardRef("MarimoPanelComm"):
+def _get_comm_class() -> Any:
global comm_class
if comm_class:
return comm_class
- from pyviz_comms import Comm
+ from pyviz_comms import Comm # type: ignore
- class MarimoPanelComm(Comm):
- def __init__(self, *args: any, **kwargs: any):
+ class MarimoPanelComm(Comm): # type: ignore
+ def __init__(self, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
self._comm = MarimoComm(
- comm_id=self.id,
+ comm_id=str(self.id),
target_name="panel.comms",
data={},
comm_manager=COMM_MANAGER,
@@ -57,10 +57,14 @@ def _get_comm_class() -> ForwardRef("MarimoPanelComm"):
@classmethod
def decode(cls, msg: SendToWidgetArgs) -> dict[str, Any]:
- buffers = {i: v for i, v in enumerate(msg.buffers)}
+ buffers: Dict[int, Any] = {
+ i: v for i, v in enumerate(msg.buffers or [])
+ }
return dict(msg.message, _buffers=buffers)
- def send(self, data=None, metadata=None, buffers=None) -> None:
+ def send(
+ self, data: Any = None, metadata: Any = None, buffers: Any = None
+ ) -> None:
buffers = buffers or []
self.comm.send(
{"content": data}, metadata=metadata, buffers=buffers
@@ -81,9 +85,9 @@ def render_extension(load_timeout: int = 500, loaded: bool = False) -> str:
if loaded and not new_exts:
return ""
- from bokeh.io.notebook import curstate
- from panel.config import config
- from panel.io.notebook import (
+ from bokeh.io.notebook import curstate # type: ignore
+ from panel.config import config # type: ignore
+ from panel.io.notebook import ( # type: ignore
CDN,
INLINE,
Resources,
@@ -101,18 +105,18 @@ def render_extension(load_timeout: int = 500, loaded: bool = False) -> str:
prev_resources = settings.resources(default="server")
user_resources = settings.resources._user_value is not _Unset
nb_endpoint = not state._is_pyodide
- resources = Resources.from_bokeh(resources, notebook=nb_endpoint)
+ resources = Resources.from_bokeh(resources, notebook=nb_endpoint) # type: ignore[no-untyped-call]
try:
- bundle = bundle_resources(
+ bundle = bundle_resources( # type: ignore[no-untyped-call]
None,
resources,
notebook=nb_endpoint,
reloading=loaded,
enable_mathjax="auto",
)
- configs, requirements, exports, skip_imports = require_components()
+ configs, requirements, exports, skip_imports = require_components() # type: ignore[no-untyped-call]
ipywidget = "ipywidgets_bokeh" in sys.modules
- bokeh_js = _autoload_js(
+ bokeh_js = _autoload_js( # type: ignore[no-untyped-call]
bundle=bundle,
configs=configs,
requirements=requirements,
@@ -128,10 +132,10 @@ def render_extension(load_timeout: int = 500, loaded: bool = False) -> str:
else:
settings.resources.unset_value()
loaded_extensions.extend(new_exts)
- return bokeh_js
+ return bokeh_js # type: ignore[no-any-return]
-def render_component(obj) -> Tuple[str, dict[str, Any], dict[str, Any]]:
+def render_component(obj: Any) -> Tuple[str, dict[str, Any], dict[str, Any]]:
from bokeh.document import Document
from bokeh.embed.util import standalone_docs_json_and_render_items
from panel.io.model import add_to_doc
@@ -146,7 +150,7 @@ def render_component(obj) -> Tuple[str, dict[str, Any], dict[str, Any]]:
[root], suppress_callback_warning=True
)
render_json = render_item.to_json()
- return ref, docs_json, render_json
+ return ref, docs_json, render_json # type: ignore[return-value]
@mddoc
@@ -187,7 +191,7 @@ class panel(UIElement[T, T]):
self._initialized = False
ref, docs_json, render_json = render_component(obj)
- self._manager = PanelCommManager(plot_id=ref)
+ self._manager = PanelCommManager(plot_id=ref) # type: ignore[no-untyped-call]
global loaded_extension
extension = render_extension(loaded=loaded_extension == id(self))
@@ -196,7 +200,7 @@ class panel(UIElement[T, T]):
super().__init__(
component_name="marimo-panel",
- initial_value=None,
+ initial_value=dict(),
label="",
args={
"extension": extension,
@@ -213,7 +217,7 @@ class panel(UIElement[T, T]):
),
)
- def _handle_msg(self, ref, msg) -> None:
+ def _handle_msg(self, ref: str, msg: Any) -> None:
comm = self.obj._comms[ref][0]
msg = comm.decode(msg)
self.obj._on_msg(ref, self._manager, msg)
diff --git a/pyproject.toml b/pyproject.toml
index 3f51caa2e9..58684ec582 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -145,6 +145,7 @@ installer = "uv"
dependencies = [
"mypy~=1.10.1",
# Types for mypy
+ "panel~=1.5.3",
"polars~=1.9.0",
"narwhals>=1.9.0",
"matplotlib>=3.8.0",