Skip to content

Commit 9103999

Browse files
committed
Improve typing annotations
We now also make the Sample3Phase.map() method more generic, to return the same type as self. Signed-off-by: Leandro Lucarella <[email protected]>
1 parent 00c3486 commit 9103999

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

src/frequenz/sdk/timeseries/_base_types.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,10 @@
33

44
"""Timeseries basic types."""
55

6-
from __future__ import annotations
7-
86
import functools
97
from dataclasses import dataclass, field
108
from datetime import datetime, timezone
11-
from typing import Callable, Iterator, Optional, overload
9+
from typing import Callable, Iterator, Self, overload
1210

1311
UNIX_EPOCH = datetime.fromtimestamp(0.0, tz=timezone.utc)
1412
"""The UNIX epoch (in UTC)."""
@@ -30,7 +28,7 @@ class Sample:
3028
timestamp: datetime = field(compare=True)
3129
"""The time when this sample was generated."""
3230

33-
value: Optional[float] = field(compare=False, default=None)
31+
value: float | None = field(compare=False, default=None)
3432
"""The value of this sample."""
3533

3634

@@ -46,13 +44,13 @@ class Sample3Phase:
4644

4745
timestamp: datetime
4846
"""The time when this sample was generated."""
49-
value_p1: Optional[float]
47+
value_p1: float | None
5048
"""The value of the 1st phase in this sample."""
5149

52-
value_p2: Optional[float]
50+
value_p2: float | None
5351
"""The value of the 2nd phase in this sample."""
5452

55-
value_p3: Optional[float]
53+
value_p3: float | None
5654
"""The value of the 3rd phase in this sample."""
5755

5856
def __iter__(self) -> Iterator[float | None]:
@@ -117,7 +115,7 @@ def min(self, default: float | None = None) -> float | None:
117115

118116
def map(
119117
self, function: Callable[[float], float], default: float | None = None
120-
) -> Sample3Phase:
118+
) -> Self:
121119
"""Apply the given function on each of the phase values and return the result.
122120
123121
If a phase value is `None`, replace it with `default` instead.
@@ -127,10 +125,10 @@ def map(
127125
default: The value to apply if a phase value is `None`.
128126
129127
Returns:
130-
A new `Sample3Phase` instance, with the given function applied on values
131-
for each of the phases.
128+
A new instance, with the given function applied on values for each of the
129+
phases.
132130
"""
133-
return Sample3Phase(
131+
return self.__class__(
134132
timestamp=self.timestamp,
135133
value_p1=default if self.value_p1 is None else function(self.value_p1),
136134
value_p2=default if self.value_p2 is None else function(self.value_p2),

0 commit comments

Comments
 (0)