Skip to content

Commit 5789a73

Browse files
committed
to_compact: support uncertainties' Magnitudes
Fix #584, make to_compact also raise a TypeError instead of a RuntimeWarning.
1 parent 29a139f commit 5789a73

File tree

2 files changed

+7
-14
lines changed

2 files changed

+7
-14
lines changed

pint/facets/plain/qto.py

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@
44

55
import bisect
66
import math
7-
import numbers
8-
import warnings
97

108
from ...util import infer_base_unit
119
from ...compat import (
@@ -100,18 +98,8 @@ def to_compact(
10098
<Quantity(10.0, 'millinewton')>
10199
"""
102100

103-
if not isinstance(quantity.magnitude, numbers.Number):
104-
msg = "to_compact applied to non numerical types " "has an undefined behavior."
105-
w = RuntimeWarning(msg)
106-
warnings.warn(w, stacklevel=2)
107-
return quantity
108101

109-
if (
110-
quantity.unitless
111-
or quantity.magnitude == 0
112-
or math.isnan(quantity.magnitude)
113-
or math.isinf(quantity.magnitude)
114-
):
102+
if quantity.unitless:
115103
return quantity
116104

117105
SI_prefixes: dict[int, str] = {}
@@ -137,6 +125,11 @@ def to_compact(
137125
q_base = quantity.to(unit)
138126

139127
magnitude = q_base.magnitude
128+
# Support uncertainties
129+
if hasattr(magnitude, 'nominal_value'):
130+
magnitude = magnitude.nominal_value
131+
if magnitude == 0 or math.isnan(magnitude) or math.isinf(magnitude):
132+
return quantity
140133

141134
units = list(q_base._units.items())
142135
units_numerator = [a for a in units if a[1] > 0]

pint/testsuite/test_quantity.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -831,7 +831,7 @@ def test_limits_magnitudes(self):
831831
def test_nonnumeric_magnitudes(self):
832832
ureg = self.ureg
833833
x = "some string" * ureg.m
834-
with pytest.warns(RuntimeWarning):
834+
with pytest.raises(TypeError):
835835
self.compare_quantity_compact(x, x)
836836

837837
def test_very_large_to_compact(self):

0 commit comments

Comments
 (0)