From ee198f004609bbd9fa927a227b16425019d25318 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jules=20Ch=C3=A9ron?= Date: Wed, 2 Mar 2022 22:09:49 +0100 Subject: [PATCH 1/2] Fix to_reduced_units with dimensionless units Fix #919 --- CHANGES | 1 + pint/registry.py | 2 ++ pint/testsuite/test_quantity.py | 7 +++++++ 3 files changed, 10 insertions(+) diff --git a/CHANGES b/CHANGES index 720de5092..a8366b64e 100644 --- a/CHANGES +++ b/CHANGES @@ -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) ### Breaking Changes diff --git a/pint/registry.py b/pint/registry.py index 6f8ff4039..af39e33cb 100644 --- a/pint/registry.py +++ b/pint/registry.py @@ -830,6 +830,8 @@ def _get_dimensionality_ratio(self, unit1, unit2): return 1 dim1, dim2 = (self.get_dimensionality(unit) for unit in (unit1, unit2)) + if dim1 == dim2: + return 1 if not dim1 or not dim2 or dim1.keys() != dim2.keys(): # not comparable return None diff --git a/pint/testsuite/test_quantity.py b/pint/testsuite/test_quantity.py index c29fd19f5..520ccc6fe 100644 --- a/pint/testsuite/test_quantity.py +++ b/pint/testsuite/test_quantity.py @@ -664,6 +664,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) + # TODO: do not subclass from QuantityTestCase class TestQuantityToCompact(QuantityTestCase): From 0145fd08ef07d262069aaf2ebba50fecffd9d158 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jules=20Ch=C3=A9ron?= <43635101+jules-ch@users.noreply.github.com> Date: Mon, 28 Mar 2022 13:33:34 +0200 Subject: [PATCH 2/2] Update pint/registry.py Co-authored-by: keewis --- pint/registry.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pint/registry.py b/pint/registry.py index af39e33cb..8a724797f 100644 --- a/pint/registry.py +++ b/pint/registry.py @@ -832,7 +832,7 @@ def _get_dimensionality_ratio(self, unit1, unit2): dim1, dim2 = (self.get_dimensionality(unit) for unit in (unit1, unit2)) if dim1 == dim2: return 1 - if not dim1 or not dim2 or dim1.keys() != dim2.keys(): # not comparable + 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())