Skip to content

Commit 504af7a

Browse files
authored
fix: Use the correct unit registry in pint (#275)
As it turns out, using `pint.Quantity(val, unit)` uses a different registry than `val * unit` when we want to use the registry of `unit`
1 parent 2f193b9 commit 504af7a

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

src/hepunits/pint.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def to_clhep(val: pint.Quantity | pint.Unit) -> float:
6565
9.800000000000001e-15
6666
"""
6767
clhep_unit = _unit_from(val)
68-
q = pint.Quantity(1.0, val) if isinstance(val, pint.Unit) else val
68+
q = (1.0 * val) if isinstance(val, pint.Unit) else val
6969
return q.to(clhep_unit).magnitude # type: ignore[no-any-return]
7070

7171

@@ -92,4 +92,4 @@ def from_clhep(val: float, unit: pint.Unit) -> pint.Quantity:
9292
<Quantity(299792458.0, 'meter / second')>
9393
"""
9494
clhep_unit = _unit_from(unit)
95-
return pint.Quantity(val, clhep_unit).to(unit)
95+
return (val * clhep_unit).to(unit)

tests/test_pint.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,12 @@ def test_unsupported_dimension():
4545
ureg = pint.UnitRegistry()
4646
with pytest.raises(ValueError, match="Unsupported dimension"):
4747
to_clhep(1 * ureg.kelvin)
48+
49+
50+
def test_consistent_registry():
51+
ureg = pint.UnitRegistry()
52+
53+
a = 1 * hepunits.mm
54+
b = 3 * ureg.nanosecond
55+
assert a * to_clhep(b) == 3 * hepunits.mm * hepunits.nanosecond
56+
assert from_clhep(a, ureg.mm) * b == 3 * ureg.mm * ureg.nanosecond

0 commit comments

Comments
 (0)