diff --git a/CHANGES b/CHANGES index de1c3bccb..d51cab876 100644 --- a/CHANGES +++ b/CHANGES @@ -11,6 +11,7 @@ Pint Changelog - Switch from appdirs to platformdirs. - Fixes issues related to GenericPlainRegistry.__getattr__ type (PR #2038, Issues #1946 and #1804) - Removed deprecated references in documentation and tests (PR #2058, Issue #2057) +- Fixed issue with `.to_compact` and Magnitudes with uncertainties / Quantities with units (PR #2053, issue #2044) 0.24.1 (2024-06-24) diff --git a/pint/facets/plain/qto.py b/pint/facets/plain/qto.py index 22176491d..9d8b7f611 100644 --- a/pint/facets/plain/qto.py +++ b/pint/facets/plain/qto.py @@ -110,12 +110,12 @@ def to_compact( ) return quantity - if ( - quantity.unitless - or quantity.magnitude == 0 - or math.isnan(quantity.magnitude) - or math.isinf(quantity.magnitude) - ): + qm = ( + quantity.magnitude + if not hasattr(quantity.magnitude, "nominal_value") + else quantity.magnitude.nominal_value + ) + if quantity.unitless or qm == 0 or math.isnan(qm) or math.isinf(qm): return quantity SI_prefixes: dict[int, str] = {} diff --git a/pint/testsuite/test_issues.py b/pint/testsuite/test_issues.py index 847f269f0..60598a595 100644 --- a/pint/testsuite/test_issues.py +++ b/pint/testsuite/test_issues.py @@ -400,7 +400,7 @@ def test_angstrom_creation(self, module_registry): module_registry.Quantity(2, "Å") def test_alternative_angstrom_definition(self, module_registry): - module_registry.Quantity(2, "\u212B") + module_registry.Quantity(2, "\u212b") def test_micro_creation_U03bc(self, module_registry): module_registry.Quantity(2, "μm") @@ -1331,3 +1331,18 @@ def test_issue2007(): assert f"{q:~C}" == "1" assert f"{q:~D}" == "1" assert f"{q:~H}" == "1" + + +@helpers.requires_uncertainties() +def test_issue2044(): + ureg = UnitRegistry() + # First make sure this doesn't fail completely (A Measurement) + q = ureg.Quantity(10_000, "m").plus_minus(0.01).to_compact() + assert_almost_equal(q.m.n, 10.0) + assert q.u == "kilometers" + # Similarly, for a Ufloat with units + from uncertainties import ufloat + + q = (ufloat(10_000, 0.01) * ureg.m).to_compact() + assert_almost_equal(q.m.n, 10.0) + assert q.u == "kilometers"