From bac90ab067d7437de875ec57d90d863169e70429 Mon Sep 17 00:00:00 2001 From: Justus Magin Date: Mon, 25 Sep 2023 06:46:48 +0200 Subject: [PATCH] adapt to NEP 51 (#8064) * convert string and bytes items to standard python types * [test-upstream] * modify the expected error message --- xarray/core/formatting.py | 2 ++ xarray/tests/test_dataset.py | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/xarray/core/formatting.py b/xarray/core/formatting.py index 3bfe902f0a3..942bf5891ca 100644 --- a/xarray/core/formatting.py +++ b/xarray/core/formatting.py @@ -160,6 +160,8 @@ def format_item(x, timedelta_format=None, quote_strings=True): if isinstance(x, (np.timedelta64, timedelta)): return format_timedelta(x, timedelta_format=timedelta_format) elif isinstance(x, (str, bytes)): + if hasattr(x, "dtype"): + x = x.item() return repr(x) if quote_strings else x elif hasattr(x, "dtype") and np.issubdtype(x.dtype, np.floating): return f"{x.item():.4}" diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index c832663ecff..3fb29e01ebb 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -4116,7 +4116,8 @@ def test_setitem(self) -> None: data4[{"dim2": [2, 3]}] = data3["var1"][{"dim2": [3, 4]}].values data5 = data4.astype(str) data5["var4"] = data4["var1"] - err_msg = "could not convert string to float: 'a'" + # convert to `np.str_('a')` once `numpy<2.0` has been dropped + err_msg = "could not convert string to float: .*'a'.*" with pytest.raises(ValueError, match=err_msg): data5[{"dim2": 1}] = "a"