Skip to content

Commit

Permalink
to_compact: support uncertainties' Magnitudes
Browse files Browse the repository at this point in the history
Fix #584, make to_compact also raise a TypeError instead of a
RuntimeWarning.
  • Loading branch information
doronbehar committed Dec 30, 2023
1 parent 29a139f commit 5789a73
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 14 deletions.
19 changes: 6 additions & 13 deletions pint/facets/plain/qto.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

import bisect
import math
import numbers
import warnings

from ...util import infer_base_unit
from ...compat import (
Expand Down Expand Up @@ -100,18 +98,8 @@ def to_compact(
<Quantity(10.0, 'millinewton')>
"""

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

if (
quantity.unitless
or quantity.magnitude == 0
or math.isnan(quantity.magnitude)
or math.isinf(quantity.magnitude)
):
if quantity.unitless:
return quantity

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

magnitude = q_base.magnitude
# Support uncertainties
if hasattr(magnitude, 'nominal_value'):
magnitude = magnitude.nominal_value
if magnitude == 0 or math.isnan(magnitude) or math.isinf(magnitude):
return quantity

units = list(q_base._units.items())
units_numerator = [a for a in units if a[1] > 0]
Expand Down
2 changes: 1 addition & 1 deletion pint/testsuite/test_quantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -831,7 +831,7 @@ def test_limits_magnitudes(self):
def test_nonnumeric_magnitudes(self):
ureg = self.ureg
x = "some string" * ureg.m
with pytest.warns(RuntimeWarning):
with pytest.raises(TypeError):
self.compare_quantity_compact(x, x)

def test_very_large_to_compact(self):
Expand Down

0 comments on commit 5789a73

Please sign in to comment.