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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: formatter registration when running as a script (#1896)
Akshay Agrawalaa19fe6212e2
diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.pyindex 80c82437fd..f1096f6bcb 100644--- a/marimo/_output/formatters/formatters.py+++ b/marimo/_output/formatters/formatters.py@@ -68,6 +68,21 @@ def register_formatters() -> None:case, the trade-off is worth it."""+ # For modules that are already imported, register their formatters+ # immediately; their import hook wouldn't be triggered since they are+ # already imported. This is relevant when executing as a script.+ pre_registered: set[str] = set()+ for package, factory in THIRD_PARTY_FACTORIES.items():+ if package in sys.modules:+ factory.register()+ pre_registered.add(package)++ third_party_factories = {+ package: factory+ for package, factory in THIRD_PARTY_FACTORIES.items()+ if package not in pre_registered+ }+# We loop over all MetaPathFinders, monkey-patching them to run third-party# formatters whenever a supported third-party package is imported (in# particular, when its module is exec'd). This ensures that formatters are@@ -107,7 +122,7 @@ def register_formatters() -> None:if spec is None:return spec- if spec.loader is not None and fullname in THIRD_PARTY_FACTORIES:+ if spec.loader is not None and fullname in third_party_factories:# We're now in the process of importing a module with# an associated formatter factory. We'll hook into its# loader to register the formatters.diff --git a/tests/_output/formatters/test_formatters.py b/tests/_output/formatters/test_formatters.pyindex c74a6fd762..d05b4c53f6 100644--- a/tests/_output/formatters/test_formatters.py+++ b/tests/_output/formatters/test_formatters.py@@ -2,6 +2,8 @@ from __future__ import annotationsimport importlibimport os.path+import sys+from unittest.mock import Mock, patchimport pytest@@ -125,3 +127,16 @@ def test_broken_formatter():formatted = try_format(obj)assert formatted.traceback is not Noneassert "Broken Formatter" in formatted.traceback+++@patch(+ "marimo._output.formatters.formatters.THIRD_PARTY_FACTORIES",+ new_callable=dict,+)[email protected](sys.modules, {"fake_module": Mock()})+def test_pre_imported_formatter(mock_third_party_factories):+ mock_factory = Mock()+ mock_third_party_factories["fake_module"] = mock_factory++ register_formatters()+ assert mock_factory.register.call_count == 1