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 to_reduced_units with dimensionless units #1481

Merged
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
1 change: 1 addition & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ Pint Changelog
- Add `pint.testing` with functions to compare pint objects in tests (Issue #1421).
- Fix handling modulo & floordiv operator in pint_eval (Issue #1470)
- Fix `to_compact` and `infer_base_unit` for non-float non_int_type.
- Fix `to_reduced_units` to work with dimensionless units. (Issue #919)
- Fix parsing of units string with same canonalized name (Issue #1441 & #1142)

### Breaking Changes
Expand Down
4 changes: 3 additions & 1 deletion pint/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -830,7 +830,9 @@ def _get_dimensionality_ratio(self, unit1, unit2):
return 1

dim1, dim2 = (self.get_dimensionality(unit) for unit in (unit1, unit2))
if not dim1 or not dim2 or dim1.keys() != dim2.keys(): # not comparable
if dim1 == dim2:
return 1
elif not dim1 or not dim2 or dim1.keys() != dim2.keys(): # not comparable
return None

ratios = (dim2[key] / val for key, val in dim1.items())
Expand Down
7 changes: 7 additions & 0 deletions pint/testsuite/test_quantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,13 @@ def test_to_reduced_units(self):
q = self.Q_(0.5, "g*t/kg")
helpers.assert_quantity_equal(q.to_reduced_units(), self.Q_(0.5, "kg"))

def test_to_reduced_units_dimensionless(self):
ureg = UnitRegistry(preprocessors=[lambda x: x.replace("%", " percent ")])
ureg.define("percent = 0.01 count = %")
Q_ = ureg.Quantity
reduced_quantity = (Q_("1 s") * Q_("5 %") / Q_("1 count")).to_reduced_units()
assert reduced_quantity == ureg.Quantity(0.05, ureg.second)

@pytest.mark.parametrize(
("unit_str", "expected_unit"),
[
Expand Down