Skip to content

Commit cb458ea

Browse files
committed
Allow all quantities multiplication by float | Percentage
This is only applying a factor so it should be safe for any Quantity. Signed-off-by: Leandro Lucarella <luca-frequenz@llucax.com>
1 parent 1c3de6b commit cb458ea

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

src/frequenz/sdk/timeseries/_quantities.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -970,6 +970,23 @@ def as_megawatt_hours(self) -> float:
970970
"""
971971
return self._base_value / 1e6
972972

973+
def __mul__(self, other: float | Percentage) -> Self:
974+
"""Scale this energy by a percentage.
975+
976+
Args:
977+
other: The percentage by which to scale this energy.
978+
979+
Returns:
980+
The scaled energy.
981+
"""
982+
match other:
983+
case float():
984+
return self._new(self._base_value * other)
985+
case Percentage():
986+
return self._new(self._base_value * other.as_fraction())
987+
case _:
988+
return NotImplemented
989+
973990
@overload
974991
def __truediv__(self, other: timedelta) -> Power:
975992
"""Return a power from dividing this energy by the given duration.

tests/timeseries/test_quantities.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -592,11 +592,12 @@ def test_invalid_multiplications() -> None:
592592
with pytest.raises(TypeError):
593593
energy *= quantity # type: ignore
594594

595-
for quantity in [power, voltage, current, energy, Percentage.from_percent(50)]:
596-
with pytest.raises(TypeError):
597-
_ = quantity * 200.0 # type: ignore
598-
with pytest.raises(TypeError):
599-
quantity *= 200.0 # type: ignore
595+
# __mod__
596+
# for quantity in [power, voltage, current, energy, Percentage.from_percent(50)]:
597+
# with pytest.raises(TypeError):
598+
# _ = quantity * 200.0 # type: ignore
599+
# with pytest.raises(TypeError):
600+
# quantity *= 200.0 # type: ignore
600601

601602

602603
# We can't use _QUANTITY_TYPES here, because it will break the tests, as hypothesis

0 commit comments

Comments
 (0)