From 1b3b73725796c9ac0404d8a3f4f72c453d6cc9e2 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 8 Dec 2025 16:17:21 +0100 Subject: [PATCH 1/2] make error message more clear --- xarray/coding/common.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xarray/coding/common.py b/xarray/coding/common.py index a624c8fa57e..4a847f11ef0 100644 --- a/xarray/coding/common.py +++ b/xarray/coding/common.py @@ -113,7 +113,7 @@ def safe_setitem(dest, key: Hashable, value, name: T_Name = None): if key in dest: var_str = f" on variable {name!r}" if name else "" raise ValueError( - f"failed to prevent overwriting existing key {key} in attrs{var_str}. " + f"Key {key} already exists in attrs{var_str}, and will not be overwritten. " "This is probably an encoding field used by xarray to describe " "how a variable is serialized. To proceed, remove this key from " "the variable's attributes manually." From fad54c8b5850e586133b6f498761716d6af2e018 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 8 Dec 2025 16:52:40 +0100 Subject: [PATCH 2/2] improve error message and update tests --- xarray/coding/common.py | 2 +- xarray/tests/test_coding_times.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/xarray/coding/common.py b/xarray/coding/common.py index 4a847f11ef0..2e8d5b0c8bc 100644 --- a/xarray/coding/common.py +++ b/xarray/coding/common.py @@ -113,7 +113,7 @@ def safe_setitem(dest, key: Hashable, value, name: T_Name = None): if key in dest: var_str = f" on variable {name!r}" if name else "" raise ValueError( - f"Key {key} already exists in attrs{var_str}, and will not be overwritten. " + f"Key '{key}' already exists in attrs{var_str}, and will not be overwritten. " "This is probably an encoding field used by xarray to describe " "how a variable is serialized. To proceed, remove this key from " "the variable's attributes manually." diff --git a/xarray/tests/test_coding_times.py b/xarray/tests/test_coding_times.py index 475ef4252fd..1bb533dc7d8 100644 --- a/xarray/tests/test_coding_times.py +++ b/xarray/tests/test_coding_times.py @@ -2088,7 +2088,7 @@ def test_timedelta_decode_via_dtype_invalid_encoding() -> None: attrs = {"dtype": "timedelta64[s]", "units": "seconds"} encoding = {"units": "foo"} encoded = Variable(["time"], [0, 1, 2], attrs=attrs, encoding=encoding) - with pytest.raises(ValueError, match="failed to prevent"): + with pytest.raises(ValueError, match=r"Key .* already exists"): conventions.decode_cf_variable("timedeltas", encoded) @@ -2097,7 +2097,7 @@ def test_timedelta_encode_via_dtype_invalid_attribute(attribute) -> None: timedeltas = pd.timedelta_range(0, freq="D", periods=3) attrs = {attribute: "foo"} variable = Variable(["time"], timedeltas, attrs=attrs) - with pytest.raises(ValueError, match="failed to prevent"): + with pytest.raises(ValueError, match=r"Key .* already exists"): conventions.encode_cf_variable(variable)