From 4d0d1245d5a35d0b7f64a7bae149259edaf8d04f Mon Sep 17 00:00:00 2001 From: Marc Wouts Date: Wed, 19 Jun 2024 22:09:02 +0100 Subject: [PATCH] WIP show dicts using str --- src/itables/datatables_format.py | 5 +++++ src/itables/version.py | 2 +- tests/test_polars.py | 13 +++++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/itables/datatables_format.py b/src/itables/datatables_format.py index 5fb3b861..df049eef 100644 --- a/src/itables/datatables_format.py +++ b/src/itables/datatables_format.py @@ -121,6 +121,7 @@ def datatables_rows(df, count=None, warn_on_unexpected_types=False, pure_json=Fa or (x.dtype == pl.UInt64 and (x > JS_MAX_SAFE_INTEGER).any()) for x in (df[col] for col in df.columns) ) + data = replace_dicts_with_strings(data) js = json.dumps(data, cls=generate_encoder(False), allow_nan=not pure_json) if has_bigints: @@ -129,6 +130,10 @@ def datatables_rows(df, count=None, warn_on_unexpected_types=False, pure_json=Fa return js +def replace_dicts_with_strings(data): + return [[str(x) if isinstance(x, dict) else x for x in row] for row in data] + + def n_suffix_for_bigints(js, pure_json=False): def n_suffix(matchobj): if pure_json: diff --git a/src/itables/version.py b/src/itables/version.py index 2ad9da8a..97f34620 100644 --- a/src/itables/version.py +++ b/src/itables/version.py @@ -1,3 +1,3 @@ """ITables' version number""" -__version__ = "2.1.4" +__version__ = "2.1.5-dev" diff --git a/tests/test_polars.py b/tests/test_polars.py index 23523943..7cd0acc8 100644 --- a/tests/test_polars.py +++ b/tests/test_polars.py @@ -38,3 +38,16 @@ def test_encode_mixed_contents(): datatables_rows(df) == '[[BigInt("1666767918216000000"), 1699300000000, 0.9510565400123596, -0.30901700258255005]]' ) + + +def test_value_counts_shown_as_string(): + """ + We don't want to pass dicts to datatable + as these appear as 'Object', cf. #290 + """ + count = polars.DataFrame(["id_1"], schema={"col_1"}).select( + polars.col("col_1").value_counts() + ) + assert datatables_rows(count) == [ + ["{'col_1': 'id_1', 'count': 1}"] + ] # e.g. a str, not a dict