From 0faac0760cf36a72d23463d5012644d751b4c8d7 Mon Sep 17 00:00:00 2001 From: andrewgsavage Date: Sun, 28 Jul 2024 01:12:52 +0100 Subject: [PATCH] add error for prefixed non multi units (#1998) --- CHANGES | 2 ++ pint/facets/plain/registry.py | 12 +++++++++++- pint/testsuite/test_unit.py | 5 +++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/CHANGES b/CHANGES index bfe99d479..15d479972 100644 --- a/CHANGES +++ b/CHANGES @@ -45,6 +45,8 @@ Pint Changelog (PR #1949) - Fix unhandled TypeError when auto_reduce_dimensions=True and non_int_type=Decimal (PR #1853) +- Creating prefixed offset units now raises an error. + (PR #1998) - Improved error message in `get_dimensionality()` when non existent units are passed. (PR #1874, Issue #1716) diff --git a/pint/facets/plain/registry.py b/pint/facets/plain/registry.py index c5c0be783..325f2c315 100644 --- a/pint/facets/plain/registry.py +++ b/pint/facets/plain/registry.py @@ -60,7 +60,12 @@ UnitLike, ) from ...compat import Self, TypeAlias, deprecated -from ...errors import DimensionalityError, RedefinitionError, UndefinedUnitError +from ...errors import ( + DimensionalityError, + OffsetUnitCalculusError, + RedefinitionError, + UndefinedUnitError, +) from ...pint_eval import build_eval_tree from ...util import ( ParserHelper, @@ -667,6 +672,11 @@ def get_name(self, name_or_alias: str, case_sensitive: bool | None = None) -> st ) if prefix: + if not self._units[unit_name].is_multiplicative: + raise OffsetUnitCalculusError( + "Prefixing a unit requires multiplying the unit." + ) + name = prefix + unit_name symbol = self.get_symbol(name, case_sensitive) prefix_def = self._prefixes[prefix] diff --git a/pint/testsuite/test_unit.py b/pint/testsuite/test_unit.py index 2156bbafd..1cca93cec 100644 --- a/pint/testsuite/test_unit.py +++ b/pint/testsuite/test_unit.py @@ -1043,3 +1043,8 @@ def test_alias(self): # Define against unknown name with pytest.raises(KeyError): ureg.define("@alias notexist = something") + + def test_prefix_offset_units(self): + ureg = UnitRegistry() + with pytest.raises(errors.OffsetUnitCalculusError): + ureg.parse_units("kilodegree_Celsius")