Skip to content

Commit

Permalink
Fix TypeError when combining auto_reduce_dimensions=True and non_int_…
Browse files Browse the repository at this point in the history
…type=Decimal (#1853)
  • Loading branch information
jonemo authored May 12, 2024
1 parent 7262388 commit c0501ff
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
4 changes: 3 additions & 1 deletion CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -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)
-----------------
Expand Down
7 changes: 7 additions & 0 deletions pint/testsuite/test_issues.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
[
Expand Down
9 changes: 7 additions & 2 deletions pint/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]

Expand All @@ -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
Expand Down

0 comments on commit c0501ff

Please sign in to comment.