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: stringify bare pint values in JSON encoding (#10242)

Shahmir Varqhaeff020509e9d
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index c6a918a7e7..493bfeecc5 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -225,6 +225,7 @@ class DependencyManager:
ruff = Dependency("ruff")
black = Dependency("black")
geopandas = Dependency("geopandas")
+ pint = Dependency("pint")
opentelemetry = Dependency("opentelemetry")
anthropic = Dependency("anthropic")
google_ai = Dependency("google.genai")
diff --git a/marimo/_messaging/msgspec_encoder.py b/marimo/_messaging/msgspec_encoder.py
index b908729f6c..696c49776d 100644
--- a/marimo/_messaging/msgspec_encoder.py
+++ b/marimo/_messaging/msgspec_encoder.py
@@ -119,6 +119,15 @@ def enc_hook(obj: Any) -> Any:
return json.loads(to_json(date_format="iso"))
+ # pint dumps as nested dicts/slots via __dict__; stringify for display.
+ if DependencyManager.pint.imported():
+ import pint # type: ignore[import-untyped,import-not-found]
+
+ if isinstance(
+ obj, (pint.Quantity, pint.Unit, pint.util.UnitsContainer)
+ ):
+ return str(obj)
+
# Handle shapely geometry objects from geopandas
if DependencyManager.geopandas.imported():
try:
diff --git a/marimo/_smoke_tests/pandas/pint_tables.py b/marimo/_smoke_tests/pandas/pint_tables.py
new file mode 100644
index 0000000000..77f93a2bba
--- /dev/null
+++ b/marimo/_smoke_tests/pandas/pint_tables.py
@@ -0,0 +1,139 @@
+# /// script
+# requires-python = ">=3.13"
+# dependencies = [
+# "marimo",
+# "pandas",
+# "pint",
+# "pint-pandas",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.23.14"
+app = marimo.App(width="medium")
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ # Pint table / JSON display
+
+ Smoke test for pint values in rich tables and other JSON-encoded outputs.
+
+ Related: [marimo#9947](https://github.com/marimo-team/marimo/issues/9947)
+
+ Values should be human-readable (e.g. `1.0 meter`, `1 second`), not nested
+ `_magnitude` / `_units` / `_non_int_type` blobs.
+ """)
+ return
+
+
+def _():
+ import marimo as mo
+ import pandas as pd
+ import pint
+ import pint_pandas # noqa: F401 — registers pint dtypes with pandas
+
+ return mo, pd, pint
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## DataFrame: pint dtype + object `Quantity` column
+
+ `meters` uses `pint[meter]`; `mixed` is object-dtype bare `pint.Quantity`.
+ """)
+ return
+
+
+def _(mo, pd, pint):
+ df_mixed = pd.DataFrame(
+ data={
+ "regular": [1, 2, 3, 7 / 9],
+ "meters": pd.Series([1, 2, 3, 7 / 9], dtype="pint[meter]"),
+ "mixed": [
+ pint.Quantity("1 sec"),
+ pint.Quantity("3 min"),
+ pint.Quantity("0.3 hours"),
+ pint.Quantity("0.02 days"),
+ ],
+ }
+ )
+ mo.vstack([df_mixed, mo.plain(df_mixed)])
+ return (df_mixed,)
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## Computed pint-pandas columns
+ """)
+ return
+
+
+def _(mo, pd):
+ df_power = pd.DataFrame(
+ {
+ "torque": pd.Series([1, 2, 2, 3], dtype="pint[lbf ft]"),
+ "angular_velocity": pd.Series([1, 2, 2, 3], dtype="pint[rpm]"),
+ }
+ )
+ df_power["power"] = df_power["torque"] * df_power["angular_velocity"]
+ mo.vstack([df_power, mo.plain(df_power), df_power.dtypes])
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## Global JSON encoding (not just DataFrames)
+
+ Bare pint values and containers that go through `enc_hook` / default tables.
+ Expect readable strings, not nested dict dumps.
+ """)
+ return
+
+
+def _(mo, pint):
+ quantity = pint.Quantity("1.5 meter")
+ unit = pint.Unit("second")
+ units_container = quantity._units
+
+ mo.vstack(
+ [
+ mo.md("**Bare `Quantity` / `Unit` / `UnitsContainer`**"),
+ mo.hstack(
+ [quantity, unit, units_container],
+ justify="start",
+ gap=2,
+ ),
+ mo.md("**`mo.plain(...)`**"),
+ mo.hstack(
+ [
+ mo.plain(quantity),
+ mo.plain(unit),
+ mo.plain(units_container),
+ ],
+ justify="start",
+ gap=2,
+ ),
+ mo.md("**Default table from list-of-dicts (uses `enc_hook`)**"),
+ [
+ {"label": "length", "value": quantity},
+ {"label": "time unit", "value": unit},
+ {"label": "units container", "value": units_container},
+ {"label": "duration", "value": pint.Quantity("3 min")},
+ ],
+ ]
+ )
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/tables/extension_array_types.py b/marimo/_smoke_tests/tables/extension_array_types.py
index 040361ef7d..e441af1957 100644
--- a/marimo/_smoke_tests/tables/extension_array_types.py
+++ b/marimo/_smoke_tests/tables/extension_array_types.py
@@ -3,6 +3,7 @@
# dependencies = [
# "marimo",
# "pandas",
+# "pint",
# "pint-pandas==0.8.0",
# "awkward-pandas",
# "awkward",
@@ -36,13 +37,14 @@ def _(mo):
def _():
import marimo as mo
import pandas as pd
+ import pint
from decimal import Decimal
import awkward as ak
import awkward_pandas as akpd
import pint_pandas # noqa: F401 — registers pint dtypes with pandas
- return Decimal, ak, akpd, mo, pd
+ return Decimal, ak, akpd, mo, pd, pint
@app.cell(hide_code=True)
@@ -155,6 +157,50 @@ def _(ak, akpd, mo, pd):
return
[email protected](hide_code=True)
+def _(mo):
+ mo.md("""
+ ## Object column of bare `pint.Quantity`
+
+ Expect readable values like `1 second`, not nested `_magnitude`/`_units` dicts.
+ """)
+ return
+
+
+def _(mo, pd, pint):
+ quantity_object_series = pd.Series(
+ [
+ pint.Quantity("1 sec"),
+ pint.Quantity("3 min"),
+ pint.Quantity("0.3 hours"),
+ pint.Quantity("0.02 days"),
+ ]
+ )
+ quantity_object_df = pd.DataFrame(
+ {
+ "regular": [1, 2, 3, 7 / 9],
+ "meters": pd.Series([1, 2, 3, 7 / 9], dtype="pint[meter]"),
+ "mixed": quantity_object_series,
+ }
+ )
+ mo.vstack(
+ [
+ mo.md("**Series (object dtype)**"),
+ mo.hstack(
+ [mo.plain(quantity_object_series), quantity_object_series],
+ widths="equal",
+ ),
+ mo.md("**DataFrame (pint dtype + object Quantity column)**"),
+ mo.hstack(
+ [mo.plain(quantity_object_df), quantity_object_df],
+ widths="equal",
+ ),
+ ]
+ )
+ return
+
+
@app.cell(hide_code=True)
def _(mo):
mo.md("""
diff --git a/tests/_plugins/core/test_json_encoder.py b/tests/_plugins/core/test_json_encoder.py
index 60f33ee1a8..0aa7747d17 100644
--- a/tests/_plugins/core/test_json_encoder.py
+++ b/tests/_plugins/core/test_json_encoder.py
@@ -779,6 +779,25 @@ def test_superjson_with_bytes() -> None:
assert encoded == '"hello\x80\x81\x82"'
+def test_pint_quantity_encoding() -> None:
+ """Bare pint types encode as readable strings, not nested dicts/slots."""
+ import pint
+
+ quantity = pint.Quantity("1.5 meter")
+ unit = pint.Unit("second")
+ units_container = quantity._units
+
+ assert encode_json_str(quantity) == '"1.5 meter"'
+ assert encode_json_str(unit) == '"second"'
+ assert encode_json_str(units_container) == '"meter"'
+ # Nested values also go through enc_hook (tables, SuperJson, UI args).
+ assert (
+ encode_json_str({"q": quantity, "u": unit, "uc": units_container})
+ == '{"q":"1.5 meter","u":"second","uc":"meter"}'
+ )
+
+
@pytest.mark.parametrize(
("value", "expected"),
[
diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
index 540f0d5dd4..b183021c8a 100644
--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py
@@ -2348,6 +2348,7 @@ class TestPandasTableManager(unittest.TestCase):
def test_to_json_str_pint_pandas_series(self) -> None:
"""pint-pandas quantities display as readable strings in tables."""
import pandas as pd
+ import pint_pandas # noqa: F401 — registers pint dtypes with pandas
series = pd.Series([1, 2, 3, 4], dtype="pint[meter]")
manager = self.factory.create()(series.to_frame(name="value"))
@@ -2357,6 +2358,24 @@ class TestPandasTableManager(unittest.TestCase):
expected = [{"value": value} for value in series.astype(str)]
assert json_data == expected
+ @pytest.mark.requires("pint")
+ def test_to_json_str_object_column_of_pint_quantities(self) -> None:
+ """Object columns of bare pint.Quantity stringify instead of nested dicts."""
+ import pandas as pd
+ import pint
+
+ series = pd.Series(
+ [
+ pint.Quantity("1 sec"),
+ pint.Quantity("3 min"),
+ pint.Quantity("0.3 hours"),
+ ]
+ )
+ manager = self.factory.create()(series.to_frame(name="mixed"))
+ json_data = json.loads(manager.to_json_str())
+
+ assert json_data == [{"mixed": str(value)} for value in series]
+
def test_extension_column_needs_stringify_skips_json_primitives(
self,
) -> None: