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: cleanup of UIElements (#1395)

Akshay Agrawal254363cd8001
diff --git a/marimo/_plugins/ui/_core/registry.py b/marimo/_plugins/ui/_core/registry.py
index 955e506b01..a289cc7e19 100644
--- a/marimo/_plugins/ui/_core/registry.py
+++ b/marimo/_plugins/ui/_core/registry.py
@@ -5,6 +5,8 @@ import sys
import weakref
from typing import Any, Dict, Iterable, Mapping, TypeVar, Union
+from marimo._runtime.context.types import ContextNotInitializedError
+
if sys.version_info < (3, 10):
from typing_extensions import TypeAlias
else:
@@ -154,6 +156,8 @@ class UIElementRegistry:
return
ui_element = self._objects[object_id]()
+ del self._objects[object_id]
+
registered_python_id = (
id(ui_element) if ui_element is not None else None
)
@@ -165,9 +169,13 @@ class UIElementRegistry:
# registration of another element when a cell re-runs
return
- if ui_element is not None:
- del self._objects[object_id]
- ui_element._dispose()
+ try:
+ ctx = get_context()
+ except ContextNotInitializedError:
+ pass
+ else:
+ ctx.function_registry.delete(namespace=object_id)
+
if object_id in self._bindings:
del self._bindings[object_id]
if object_id in self._constructing_cells:
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index c93414c989..93089debb3 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import abc
import copy
import uuid
+import weakref
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
@@ -22,7 +23,6 @@ from marimo._plugins.core.web_component import JSONType, build_ui_plugin
from marimo._plugins.ui._core import ids
from marimo._runtime.context import ContextNotInitializedError, get_context
from marimo._runtime.functions import Function
-from marimo._utils.exiting import python_exiting
if TYPE_CHECKING:
from marimo._plugins.ui._impl.input import form as form_plugin
@@ -127,6 +127,19 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
self._initialize(*self._args)
self._initialized = True
+ try:
+ ctx = get_context()
+ except ContextNotInitializedError:
+ pass
+ else:
+ # When the UI element is destructed, it should be removed
+ # from the UIElementRegistry (which only holds a weakref to it).
+ finalizer = weakref.finalize(
+ self, ctx.ui_element_registry.delete, self._id, id(self)
+ )
+ # No need to clean up the registry at program teardown
+ finalizer.atexit = False
+
def _initialize(
self,
component_name: str,
@@ -220,32 +233,6 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
)
super().__init__(text=text)
- def _dispose(self) -> None:
- """Handle used by the registry to clean-up this element on removal."""
- try:
- ctx = get_context()
- ctx.function_registry.delete(namespace=self._id)
- except ContextNotInitializedError:
- pass
-
- # bind the function python_exiting to ensure it still exists at Python
- # destruction time; for graceful exits when running as a script
- def __del__(
- self, _python_exiting: Callable[..., bool] = python_exiting
- ) -> None:
- if _python_exiting():
- # imports can fail when python is exiting; clean-up
- # is not important when exiting anyway
- return
-
- try:
- ctx = get_context()
- ctx.ui_element_registry.delete(self._id, id(self))
- except ContextNotInitializedError:
- pass
-
- super().__del__()
-
@abc.abstractmethod
def _convert_value(self, value: S) -> T:
"""Converts a value from the frontend to a value for the `UIElement`