Skip to content

Commit 60516db

Browse files
authored
Support negation of quantities (#515)
2 parents 9c63e60 + 309cb2a commit 60516db

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/frequenz/sdk/timeseries/_quantities.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,16 @@ def __eq__(self, other: object) -> bool:
287287
assert isinstance(other, self.__class__)
288288
return self._base_value == other._base_value
289289

290+
def __neg__(self) -> Self:
291+
"""Return the negation of this quantity.
292+
293+
Returns:
294+
The negation of this quantity.
295+
"""
296+
negation = type(self).__new__(type(self))
297+
negation._base_value = -self._base_value
298+
return negation
299+
290300

291301
class _NoDefaultConstructible(type):
292302
"""A metaclass that disables the default constructor."""

tests/timeseries/test_quantities.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,3 +293,29 @@ def test_percentage() -> None:
293293
assert f"{pct}" == "20.4 %"
294294
assert pct.as_percent() == 20.4
295295
assert pct.as_fraction() == 0.204
296+
297+
298+
def test_neg() -> None:
299+
"""Test the negation of quantities."""
300+
power = Power.from_watts(1000.0)
301+
assert -power == Power.from_watts(-1000.0)
302+
assert -(-power) == power
303+
304+
voltage = Voltage.from_volts(230.0)
305+
assert -voltage == Voltage.from_volts(-230.0)
306+
assert -(-voltage) == voltage
307+
308+
current = Current.from_amperes(2)
309+
assert -current == Current.from_amperes(-2)
310+
assert -(-current) == current
311+
312+
energy = Energy.from_kilowatt_hours(6.2)
313+
assert -energy == Energy.from_kilowatt_hours(-6.2)
314+
315+
freq = Frequency.from_hertz(50)
316+
assert -freq == Frequency.from_hertz(-50)
317+
assert -(-freq) == freq
318+
319+
pct = Percentage.from_fraction(30)
320+
assert -pct == Percentage.from_fraction(-30)
321+
assert -(-pct) == pct

0 commit comments

Comments
 (0)