Skip to content

Give quantify errors context #43

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 12 commits into from
Apr 14, 2021
3 changes: 3 additions & 0 deletions docs/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ What's new
- rewrite :py:meth:`Dataset.pint.quantify` and :py:meth:`DataArray.pint.quantify`,
to use pint's `parse_units` instead of `parse_expression` (:pull:`40`)
By `Tom Nicholas <https://github.com/TomNicholas>`_.
- ensure the variable which causes the error is explicit if an error occurs in
:py:meth:`Dataset.pint.quantify` (:pull:`43`)
By `Tom Nicholas <https://github.com/TomNicholas>`_.
- refactor the internal conversion functions (:pull:`56`)
By `Justus Magin <https://github.com/keewis>`_.
- allow converting indexes (except :py:class:`pandas.MultiIndex`) (:pull:`56`)
Expand Down
18 changes: 11 additions & 7 deletions pint_xarray/accessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -1145,14 +1145,18 @@ def quantify(self, units=None, unit_registry=None, **unit_kwargs):

unit_attrs = conversion.extract_unit_attributes(self.ds)

units = {
name: _decide_units(unit, registry, attr)
for name, (unit, attr) in zip_mappings(units, unit_attrs).items()
if unit is not None or attr is not None
}

possible_new_units = zip_mappings(units, unit_attrs)
new_units = {}
for name, (unit, attr) in possible_new_units.items():
if unit is not None or attr is not None:
try:
new_units[name] = _decide_units(unit, registry, attr)
except Exception as e:
raise ValueError(
f"Failed to assign units to variable {name}"
) from e
return self.ds.pipe(conversion.strip_unit_attributes).pipe(
conversion.attach_units, units
conversion.attach_units, new_units
)

def dequantify(self, format=None):
Expand Down
7 changes: 6 additions & 1 deletion pint_xarray/tests/test_accessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,12 @@ def test_error_when_already_units(self, example_quantity_ds):

def test_error_on_nonsense_units(self, example_unitless_ds):
ds = example_unitless_ds
with pytest.raises(UndefinedUnitError):
with pytest.raises(ValueError):
ds.pint.quantify(units={"users": "aecjhbav"})

def test_error_indicates_problematic_variable(self, example_unitless_ds):
ds = example_unitless_ds
with pytest.raises(ValueError, match="users"):
ds.pint.quantify(units={"users": "aecjhbav"})


Expand Down