Skip to content

Use add_note() to annotate exceptions when encoding fails #10464

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ New Features
~~~~~~~~~~~~
- Expose :py:class:`~xarray.indexes.RangeIndex`, and :py:class:`~xarray.indexes.CoordinateTransformIndex` as public api
under the ``xarray.indexes`` namespace. By `Deepak Cherian <https://github.com/dcherian>`_.
- Better error messages when encoding data to be written to disk fails (:pull:`10464`).
By `Stephan Hoyer <https://github.com/shoyer>`_

Breaking changes
~~~~~~~~~~~~~~~~
Expand Down
24 changes: 18 additions & 6 deletions xarray/backends/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,9 +389,23 @@ def encode(self, variables, attributes):
attributes : dict-like

"""
variables = {k: self.encode_variable(v, name=k) for k, v in variables.items()}
attributes = {k: self.encode_attribute(v) for k, v in attributes.items()}
return variables, attributes
encoded_variables = {}
for k, v in variables.items():
try:
encoded_variables[k] = self.encode_variable(v)
except Exception as e:
e.add_note(f"Raised while encoding variable {k!r} with value {v!r}")
raise

encoded_attributes = {}
for k, v in attributes.items():
try:
encoded_attributes[k] = self.encode_attribute(v)
except Exception as e:
e.add_note(f"Raised while encoding attribute {k!r} with value {v!r}")
raise

return encoded_variables, encoded_attributes

def encode_variable(self, v, name=None):
"""encode one variable"""
Expand Down Expand Up @@ -641,9 +655,7 @@ def encode(self, variables, attributes):
variables = {
k: ensure_dtype_not_object(v, name=k) for k, v in variables.items()
}
variables = {k: self.encode_variable(v, name=k) for k, v in variables.items()}
attributes = {k: self.encode_attribute(v) for k, v in attributes.items()}
return variables, attributes
return super().encode(variables, attributes)


class BackendEntrypoint:
Expand Down
8 changes: 7 additions & 1 deletion xarray/conventions.py
Original file line number Diff line number Diff line change
Expand Up @@ -792,7 +792,13 @@ def cf_encoder(variables: T_Variables, attributes: T_Attrs):
# add encoding for time bounds variables if present.
_update_bounds_encoding(variables)

new_vars = {k: encode_cf_variable(v, name=k) for k, v in variables.items()}
new_vars = {}
for k, v in variables.items():
try:
new_vars[k] = encode_cf_variable(v, name=k)
except Exception as e:
e.add_note(f"Raised while encoding variable {k!r} with value {v!r}")
raise

# Remove attrs from bounds variables (issue #2921)
for var in new_vars.values():
Expand Down
17 changes: 17 additions & 0 deletions xarray/tests/test_backends_common.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
from __future__ import annotations

import re

import numpy as np
import pytest

import xarray as xr
from xarray.backends.common import _infer_dtype, robust_getitem
from xarray.tests import requires_scipy


class DummyFailure(Exception):
Expand Down Expand Up @@ -43,3 +47,16 @@ def test_robust_getitem() -> None:
def test_infer_dtype_error_on_mixed_types(data):
with pytest.raises(ValueError, match="unable to infer dtype on variable"):
_infer_dtype(data, "test")


@requires_scipy
def test_encoding_failure_note():
# Create an arbitrary value that cannot be encoded in netCDF3
ds = xr.Dataset({"invalid": np.array([2**63 - 1], dtype=np.int64)})
with pytest.raises(
ValueError,
match=re.escape(
"Raised while encoding variable 'invalid' with value <xarray.Variable"
),
):
ds.to_netcdf()
Loading