Skip to content

Commit

Permalink
Add early exit to Property.to_unit if units are equal
Browse files Browse the repository at this point in the history
  • Loading branch information
Maxcode123 committed Apr 9, 2024
1 parent b09862f commit 17d987f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
3 changes: 3 additions & 0 deletions src/property_utils/properties/property.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@ def to_unit(self, unit: UnitDescriptor) -> Self:
>>> T.to_unit(RelativeTemperatureUnit.FAHRENHEIT)
<Property: 212.0 °F>
"""
if self.unit == unit:
return self.__class__(unit=self.unit, value=self.value)

if not unit.isinstance_equivalent(self.unit.to_generic()):
raise PropertyUnitConversionError(
f"cannot convert {self} to ({unit}) units; 'unit' should be an instance"
Expand Down
12 changes: 6 additions & 6 deletions src/property_utils/tests/properties/test_property.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,15 +167,15 @@ def subject(self, unit):

@args({"unit": Unit1.a})
def test_with_simple_si_units(self):
self.assert_result("200.0 a")
self.assert_result("200 a")

@args({"unit": Unit1.a**2})
def test_with_dimension_si_units(self):
self.assert_result("200.0 (a^2)")
self.assert_result("200 (a^2)")

@args({"unit": (Unit1.a**2) / (Unit4.d**3)})
def test_with_composite_si_units(self):
self.assert_result("200.0 (a^2) / (d^3)")
self.assert_result("200 (a^2) / (d^3)")

@args({"unit": Unit1.A})
def test_with_simple_non_si_units(self):
Expand Down Expand Up @@ -210,7 +210,7 @@ def test_with_different_unit_type(self):

@args({"unit": Unit1.A})
def test_with_same_unit(self):
self.assert_result("105.0 A")
self.assert_result("105 A")

@args({"unit": Unit1.a})
def test_with_other_unit(self):
Expand All @@ -233,7 +233,7 @@ def test_with_different_dimension(self):

@args({"unit": Unit1.A**2})
def test_with_same_dimension(self):
self.assert_result("52.0 (A^2)")
self.assert_result("52 (A^2)")

@args({"unit": Unit1.a**2})
def test_with_other_unit(self):
Expand All @@ -256,7 +256,7 @@ def test_with_different_composite_dimension(self):

@args({"unit": (Unit1.A**2) / (Unit4.D**3)})
def test_with_same_composite_dimension(self):
self.assert_result("20.0 (A^2) / (D^3)")
self.assert_result("20 (A^2) / (D^3)")

@args({"unit": (Unit1.a**2) / (Unit4.d**3)})
def test_with_other_unit(self):
Expand Down

0 comments on commit 17d987f

Please sign in to comment.