Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(anywidget): Drop ipywidgets dependency #579

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 33 additions & 10 deletions anywidget/_descriptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ def __init__(
self._extra_state = (extra_state or {}).copy()
self._extra_state.setdefault(_ANYWIDGET_ID_KEY, _anywidget_id(obj))
self._no_view = no_view
self._callbacks = []

try:
self._obj: Callable[[], object] = weakref.ref(obj, self._on_obj_deleted)
Expand Down Expand Up @@ -397,29 +398,39 @@ def _handle_msg(self, msg: CommMessage) -> None:
elif data["method"] == "request_state":
self.send_state()

# elif method == "custom": # noqa: ERA001
# Handle a custom msg from the front-end.
# if "content" in data:
# self._handle_custom_msg(data["content"], msg["buffers"]) # noqa: ERA001
else: # pragma: no cover
elif data["method"] == "custom":
if "content" in data:
self._handle_custom_msg(data["content"], msg["buffers"])

else:
err_msg = (
f"Unrecognized method: {data['method']}. Please report this at "
"https://github.com/manzt/anywidget/issues"
)
raise ValueError(err_msg)

# def _handle_custom_msg(self, content: object, buffers: list[memoryview]):
# # TODO(manzt): handle custom callbacks # noqa: TD003
# # https://github.com/jupyter-widgets/ipywidgets/blob/6547f840edc1884c75e60386ec7fb873ba13f21c/python/ipywidgets/ipywidgets/widgets/widget.py#L662
# ...
def _handle_custom_msg(self, content: Any, buffers: list[memoryview]):
# https://github.com/jupyter-widgets/ipywidgets/blob/b78de43e12ff26e4aa16e6e4c6844a7c82a8ee1c/python/ipywidgets/ipywidgets/widgets/widget.py#L186
for callback in self._callbacks:
try:
callback(content, buffers)
except Exception:
warnings.warn(
"Error in custom message callback",
stacklevel=2,
)

def __call__(self, **kwargs: Sequence[str]) -> tuple[dict, dict] | None: # noqa: ARG002
"""Called when _repr_mimebundle_ is called on the python object."""
# NOTE: this could conceivably be a method on a Comm subclass
# (i.e. the comm knows how to represent itself as a mimebundle)
if self._no_view:
return None
return repr_mimebundle(model_id=self._comm.comm_id, repr_text=repr(self._obj()))

repr_text = repr(self._obj())
if len(repr_text) > 110:
repr_text = repr_text[:110] + "…"
return repr_mimebundle(model_id=self._comm.comm_id, repr_text=repr_text)

def sync_object_with_view(
self,
Expand Down Expand Up @@ -485,6 +496,18 @@ def unsync_object_with_view(self) -> None:
with contextlib.suppress(Exception):
self._disconnectors.pop()()

def register_callback(
self, callback: Callable[[Any, Any, list[bytes]], None]
) -> None:
self._callbacks.append(callback)

def send(
self, content: str | list | dict, buffers: list[memoryview] | None = None
) -> None:
"""Send a custom message to the front-end view."""
data = {"method": "custom", "content": content}
self._comm.send(data=data, buffers=buffers) # type: ignore[arg-type]


# ------------- Helper function --------------

Expand Down
4 changes: 2 additions & 2 deletions anywidget/_protocols.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,9 @@ class AnywidgetProtocol(Protocol):
class WidgetBase(Protocol):
"""Widget subclasses with a custom message reducer."""

def send(self, msg: str | dict | list, buffers: list[bytes]) -> None: ...
def send(self, msg: Any, buffers: list[memoryview] | list[bytes] | None) -> None: ...

def on_msg(
self,
callback: Callable[[Any, str | list | dict, list[bytes]], None],
callback: Callable[[Any, str | list | dict, list[bytes] | list[memoryview]], None],
) -> None: ...
13 changes: 2 additions & 11 deletions anywidget/_version.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,6 @@
try:
from importlib.metadata import PackageNotFoundError, version
except ImportError:
from importlib_metadata import ( # type: ignore[import-not-found, no-redef]
PackageNotFoundError,
version,
)
import importlib.metadata

try:
__version__ = version("anywidget")
except PackageNotFoundError:
__version__ = "uninstalled"
__version__ = importlib.metadata.version("anywidget")


def get_semver_version(version: str) -> str:
Expand Down
12 changes: 6 additions & 6 deletions anywidget/experimental.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,8 @@ def _decorator(cls: T) -> T:
_ANYWIDGET_COMMANDS = "_anywidget_commands"

_AnyWidgetCommand = typing.Callable[
[object, object, typing.List[bytes]],
typing.Tuple[object, typing.List[bytes]],
[object, object, list[bytes] | list[memoryview]],
tuple[object, list[bytes] | list[memoryview]],
]


Expand Down Expand Up @@ -160,14 +160,14 @@ def _register_anywidget_commands(widget: WidgetBase) -> None:

def handle_anywidget_command(
self: WidgetBase,
msg: str | list | dict,
buffers: list[bytes],
msg: typing.Any,
buffers: list[bytes] | list[memoryview],
) -> None:
if not isinstance(msg, dict) or msg.get("kind") != "anywidget-command":
return
cmd = cmds[msg["name"]]
response, buffers = cmd(widget, msg["msg"], buffers)
self.send(
response, buffers = cmd(widget, msg["msg"], buffers or [])
widget.send(
{
"id": msg["id"],
"kind": "anywidget-command-response",
Expand Down
89 changes: 25 additions & 64 deletions anywidget/widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,81 +2,42 @@

from __future__ import annotations

import ipywidgets
import traitlets.traitlets as t
from typing import Any, Callable

from ._file_contents import FileContents, VirtualFileContents
from ._util import (
_ANYWIDGET_ID_KEY,
_CSS_KEY,
_DEFAULT_ESM,
_ESM_KEY,
enable_custom_widget_manager_once,
in_colab,
repr_mimebundle,
try_file_contents,
)
from ._version import _ANYWIDGET_SEMVER_VERSION
from .experimental import _collect_anywidget_commands, _register_anywidget_commands

_PLAIN_TEXT_MAX_LEN = 110


class AnyWidget(ipywidgets.DOMWidget): # type: ignore [misc]
"""Main AnyWidget base class."""
import traitlets

_model_name = t.Unicode("AnyModel").tag(sync=True)
_model_module = t.Unicode("anywidget").tag(sync=True)
_model_module_version = t.Unicode(_ANYWIDGET_SEMVER_VERSION).tag(sync=True)

_view_name = t.Unicode("AnyView").tag(sync=True)
_view_module = t.Unicode("anywidget").tag(sync=True)
_view_module_version = t.Unicode(_ANYWIDGET_SEMVER_VERSION).tag(sync=True)

def __init__(self, *args: object, **kwargs: object) -> None:
if in_colab():
enable_custom_widget_manager_once()
from ._descriptor import MimeBundleDescriptor
from ._util import _CSS_KEY, _ESM_KEY
from .experimental import _collect_anywidget_commands, _register_anywidget_commands

anywidget_traits = {}
for key in (_ESM_KEY, _CSS_KEY):
if hasattr(self, key) and not self.has_trait(key):
value = getattr(self, key)
anywidget_traits[key] = t.Unicode(str(value)).tag(sync=True)
if isinstance(value, (VirtualFileContents, FileContents)):
value.changed.connect(
lambda new_contents, key=key: setattr(self, key, new_contents),
)

# show default _esm if not defined
if not hasattr(self, _ESM_KEY):
anywidget_traits[_ESM_KEY] = t.Unicode(_DEFAULT_ESM).tag(sync=True)
class AnyWidget(traitlets.HasTraits): # type: ignore [misc]
"""Main AnyWidget base class."""

# TODO(manzt): a better way to uniquely identify this subclasses? # noqa: TD003
# We use the fully-qualified name to get an id which we
# can use to update CSS if necessary.
anywidget_traits[_ANYWIDGET_ID_KEY] = t.Unicode(
f"{self.__class__.__module__}.{self.__class__.__name__}",
).tag(sync=True)
_repr_mimebundle_: MimeBundleDescriptor

self.add_traits(**anywidget_traits)
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
_register_anywidget_commands(self)
# Access _repr_mimebundle_ descriptor to trigger comm initialization
self._repr_mimebundle_ # noqa: B018

def __init_subclass__(cls, **kwargs: dict) -> None:
"""Coerces _esm and _css to FileContents if they are files."""
"""Create the _repr_mimebundle_ descriptor and register anywidget commands."""
super().__init_subclass__(**kwargs)
for key in (_ESM_KEY, _CSS_KEY) & cls.__dict__.keys():
# TODO(manzt): Upgrate to := when we drop Python 3.7
# https://github.com/manzt/anywidget/pull/167
file_contents = try_file_contents(getattr(cls, key))
if file_contents:
setattr(cls, key, file_contents)
extra_state = {
key: getattr(cls, key) for key in (_ESM_KEY, _CSS_KEY) & cls.__dict__.keys()
}
cls._repr_mimebundle_ = MimeBundleDescriptor(**extra_state)
_collect_anywidget_commands(cls)

def _repr_mimebundle_(self, **kwargs: dict) -> tuple[dict, dict] | None: # noqa: ARG002
plaintext = repr(self)
if len(plaintext) > _PLAIN_TEXT_MAX_LEN:
plaintext = plaintext[:110] + "…"
if self._view_name is None:
return None # type: ignore[unreachable]
return repr_mimebundle(model_id=self.model_id, repr_text=plaintext)
def send(self, msg: Any, buffers: list[memoryview] | None = None) -> None:
"""Send a message to the frontend."""
self._repr_mimebundle_.send(content=msg, buffers=buffers)

def on_msg(
self, callback: Callable[[Any, str | list | dict, list[bytes]], None]
) -> None:
"""Register a message handler."""
self._repr_mimebundle_.register_callback(callback)
22 changes: 12 additions & 10 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,6 @@ license = { text = "MIT" }
dynamic = ["version"]
readme = "README.md"
requires-python = ">=3.8"
dependencies = [
"ipywidgets>=7.6.0",
"typing-extensions>=4.2.0",
"psygnal>=0.8.1",
]
classifiers = [
"Framework :: Jupyter",
"Framework :: Jupyter :: JupyterLab",
Expand All @@ -27,22 +22,29 @@ classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
]

[project.urls]
homepage = "https://github.com/manzt/anywidget"
dependencies = [
"comm>=0.1.4",
"psygnal>=0.8.1",
"traitlets>=4.3.1",
"jupyterlab-widgets~=3.0.12", # Installs widgets extension for JupyterLab
"widgetsnbextension~=4.0.12", # Installs widgets extension for classic notebooks
]

[project.optional-dependencies]
dev = ["watchfiles>=0.18.0"]

[project.urls]
homepage = "https://github.com/manzt/anywidget"

[tool.uv]
dev-dependencies = [
"comm>=0.1.4",
"jupyterlab>=4.2.4",
"msgspec>=0.18.6",
"mypy>=1.11.1",
"pydantic>=2.5.3",
"pytest>=7.4.4",
"ruff>=0.6.1",
"typing-extensions>=4.12.2",
"watchfiles>=0.23.0",
]

Expand Down Expand Up @@ -153,5 +155,5 @@ disallow_untyped_calls = false

[[tool.mypy.overrides]]
# this might be missing in pre-commit, but they aren't typed anyway
module = ["ipywidgets", "traitlets.*", "comm", "IPython.*"]
module = ["traitlets.*", "comm", "IPython.*"]
ignore_missing_imports = true
34 changes: 10 additions & 24 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading