Skip to content
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

Fix TypeError when combining auto_reduce_dimensions=True and non_int_type=Decimal #1853

Merged
merged 9 commits into from
May 12, 2024
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
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
Loading