diff --git a/CHANGES b/CHANGES index d1200e5e3..66281cc6d 100644 --- a/CHANGES +++ b/CHANGES @@ -18,7 +18,9 @@ Pint Changelog (PR #1816) - Fix converting to offset units of higher dimension e.g. gauge pressure (PR #1949) - +- Fix unhandled TypeError when auto_reduce_dimensions=True and non_int_type=Decimal + (PR #1853) + 0.23 (2023-12-08) ----------------- diff --git a/pint/testsuite/test_issues.py b/pint/testsuite/test_issues.py index 1e0497e4a..2a0b7edf6 100644 --- a/pint/testsuite/test_issues.py +++ b/pint/testsuite/test_issues.py @@ -1179,6 +1179,13 @@ def test_issue1505(): ) # unexpected fail (magnitude should be a decimal) +def test_issue_1845(): + ur = UnitRegistry(auto_reduce_dimensions=True, non_int_type=decimal.Decimal) + # before issue 1845 these inputs would have resulted in a TypeError + assert ur("km / h * m").units == ur.Quantity("meter ** 2 / hour") + assert ur("kW / min * W").units == ur.Quantity("watts ** 2 / minute") + + @pytest.mark.parametrize( "units,spec,expected", [ diff --git a/pint/util.py b/pint/util.py index 0c40c5187..c7a7ec10c 100644 --- a/pint/util.py +++ b/pint/util.py @@ -495,7 +495,7 @@ def add(self: Self, key: str, value: Number) -> Self: UnitsContainer A copy of this container. """ - newval = self._d[key] + value + newval = self._d[key] + self._normalize_nonfloat_value(value) new = self.copy() if newval: new._d[key] = newval @@ -656,7 +656,7 @@ def __truediv__(self, other: Any): new = self.copy() for key, value in other.items(): - new._d[key] -= value + new._d[key] -= self._normalize_nonfloat_value(value) if new._d[key] == 0: del new._d[key] @@ -670,6 +670,11 @@ def __rtruediv__(self, other: Any): return self**-1 + def _normalize_nonfloat_value(self, value: Scalar) -> Scalar: + if not isinstance(value, int) and not isinstance(value, self._non_int_type): + return self._non_int_type(value) # type: ignore[no-any-return] + return value + class ParserHelper(UnitsContainer): """The ParserHelper stores in place the product of variables and