Skip to content

Commit 68805ad

Browse files
committed
Use forward type annotations
Besides improving code legibility, they are necessary for the rendered documentation to be properly cross-referenced (otherwise the types appear just as a string, without links). Signed-off-by: Leandro Lucarella <[email protected]>
1 parent f418214 commit 68805ad

File tree

7 files changed

+35
-22
lines changed

7 files changed

+35
-22
lines changed

examples/sdk_usage_example.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
Second user receives requests and set that power.
99
"""
1010

11+
from __future__ import annotations
12+
1113
import asyncio
1214
import logging
1315
from datetime import datetime, timezone
@@ -136,7 +138,7 @@ async def run(self) -> None:
136138
RuntimeError: If communication channel has been closed.
137139
"""
138140
while True:
139-
queue: "Queue[Optional[float]]" = Queue(maxsize=50)
141+
queue: Queue[Optional[float]] = Queue(maxsize=50)
140142
for _ in range(5):
141143
active_power = await self._active_power_data.receive()
142144
if active_power is None:

src/frequenz/sdk/data_handling/power.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
"""Provides support for processing power measurements from different microgrid components."""
55

6+
from __future__ import annotations
7+
68
from numbers import Real
79

810
from frequenz.api.microgrid.common_pb2 import AC
@@ -36,7 +38,7 @@ def __init__(self, complex_power: complex) -> None:
3638
self._complex_power = complex_power
3739

3840
@classmethod
39-
def from_protobuf(cls, ac_message: AC) -> "ComplexPower":
41+
def from_protobuf(cls, ac_message: AC) -> ComplexPower:
4042
"""Create a ComplexPower value from the AC type of the microgrid gRPC API.
4143
4244
Args:
@@ -54,7 +56,7 @@ def from_protobuf(cls, ac_message: AC) -> "ComplexPower":
5456
return cls(complex(active, reactive))
5557

5658
@classmethod
57-
def from_active_power(cls, active_power: float) -> "ComplexPower":
59+
def from_active_power(cls, active_power: float) -> ComplexPower:
5860
"""Create a ComplexPower value from a numerical active power value.
5961
6062
Args:
@@ -68,7 +70,7 @@ def from_active_power(cls, active_power: float) -> "ComplexPower":
6870
return cls(complex(active_power, 0))
6971

7072
@classmethod
71-
def from_reactive_power(cls, reactive_power: float) -> "ComplexPower":
73+
def from_reactive_power(cls, reactive_power: float) -> ComplexPower:
7274
"""Create a ComplexPower value from a numerical reactive power value.
7375
7476
Args:
@@ -161,15 +163,15 @@ def capacitive(self) -> float:
161163
"""
162164
return max(-self.imag, 0)
163165

164-
def __neg__(self) -> "ComplexPower":
166+
def __neg__(self) -> ComplexPower:
165167
"""Generate the negative of this value.
166168
167169
Returns:
168170
Value whose real and imaginary parts are the negative of this instance's
169171
"""
170172
return ComplexPower(-self._complex_power)
171173

172-
def __add__(self, other: object) -> "ComplexPower":
174+
def __add__(self, other: object) -> ComplexPower:
173175
"""Add this complex power value to the provided `other`.
174176
175177
Args:
@@ -183,7 +185,7 @@ def __add__(self, other: object) -> "ComplexPower":
183185

184186
return ComplexPower(self._complex_power + other._complex_power)
185187

186-
def __sub__(self, other: object) -> "ComplexPower":
188+
def __sub__(self, other: object) -> ComplexPower:
187189
"""Subtract the provided `other` from this complex power value.
188190
189191
Args:
@@ -197,7 +199,7 @@ def __sub__(self, other: object) -> "ComplexPower":
197199

198200
return ComplexPower(self._complex_power - other._complex_power)
199201

200-
def __mul__(self, other: object) -> "ComplexPower":
202+
def __mul__(self, other: object) -> ComplexPower:
201203
"""Multiply this complex power value by the provided scalar.
202204
203205
Args:
@@ -213,7 +215,7 @@ def __mul__(self, other: object) -> "ComplexPower":
213215

214216
__rmul__ = __mul__
215217

216-
def __truediv__(self, other: object) -> "ComplexPower":
218+
def __truediv__(self, other: object) -> ComplexPower:
217219
"""Divide this complex power value by the provided scalar.
218220
219221
Args:

src/frequenz/sdk/data_ingestion/microgrid_data.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
Including default standard formulas for client load, grid load, total pv production,
88
ev charging rate, battery SoC, active power, max consume and supply rate.
99
"""
10+
11+
from __future__ import annotations
12+
1013
import asyncio
1114
import logging
1215
from datetime import datetime, timezone
@@ -93,7 +96,7 @@ async def resend_formulas(self) -> None:
9396
"""Send formulas results with some period."""
9497
# Sleep first to collect initial data from all component
9598
await asyncio.sleep(self._wait_for_data_sec)
96-
tasks: List["asyncio.Task[bool]"] = []
99+
tasks: List[asyncio.Task[bool]] = []
97100
while True:
98101
start_time = datetime.now(timezone.utc)
99102
# For every formula that was updated at least once, send that formula.
@@ -175,7 +178,7 @@ def parse_formula_overrides(self, config: Config) -> Dict[str, Set[int]]:
175178

176179
# pylint: disable=unused-argument
177180
async def _reinitialize(
178-
self, config: Config, resend_formulas_task: "asyncio.Task[None]"
181+
self, config: Config, resend_formulas_task: asyncio.Task[None]
179182
) -> None:
180183
"""Reinitialize MicrogridData with updated config.
181184

src/frequenz/sdk/microgrid/component.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
"""Defines the components that can be used in a microgrid."""
55

6+
from __future__ import annotations
7+
68
from dataclasses import dataclass
79
from enum import Enum
810

@@ -28,7 +30,7 @@ class ComponentCategory(Enum):
2830

2931

3032
def _component_category_from_protobuf(
31-
component_category: "microgrid_pb.ComponentCategory.ValueType",
33+
component_category: microgrid_pb.ComponentCategory.ValueType,
3234
) -> ComponentCategory:
3335
"""Convert a protobuf ComponentCategory message to ComponentCategory enum.
3436

src/frequenz/sdk/microgrid/retry.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
"""Implementations for retry strategies."""
55

6+
from __future__ import annotations
7+
68
import random
79
from abc import ABC, abstractmethod
810
from copy import deepcopy
@@ -47,7 +49,7 @@ def reset(self) -> None:
4749
"""
4850
self._count = 0
4951

50-
def copy(self) -> "RetryStrategy":
52+
def copy(self) -> RetryStrategy:
5153
"""Create a new instance of `self`.
5254
5355
Returns:

src/frequenz/sdk/power_distribution/power_distributor.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
66
Purpose of this tool is to keep SoC level of each component at the equal level.
77
"""
8+
9+
from __future__ import annotations
10+
811
import asyncio
912
import logging
1013
from asyncio.tasks import ALL_COMPLETED
@@ -153,7 +156,7 @@ def __init__(
153156
# important. It will execute both. And later request will override the previous
154157
# one.
155158
# That is why the queue of maxsize = total number of batteries should be enough.
156-
self._request_queue: "asyncio.Queue[Tuple[Request, User]]" = asyncio.Queue(
159+
self._request_queue: asyncio.Queue[Tuple[Request, User]] = asyncio.Queue(
157160
maxsize=len(self._bat_inv_map)
158161
)
159162

@@ -315,7 +318,7 @@ def _check_request(self, request: Request) -> Optional[Result]:
315318

316319
def _remove_duplicated_requests(
317320
self, request: Request, user: User
318-
) -> List["asyncio.Task[bool]"]:
321+
) -> List[asyncio.Task[bool]]:
319322
"""Remove duplicated requests from the queue.
320323
321324
Remove old requests in which set of batteries are the same as in new request.
@@ -332,7 +335,7 @@ def _remove_duplicated_requests(
332335
batteries = request.batteries
333336

334337
good_requests: List[Tuple[Request, User]] = []
335-
to_ignore: List["asyncio.Task[bool]"] = []
338+
to_ignore: List[asyncio.Task[bool]] = []
336339

337340
while not self._request_queue.empty():
338341
prev_request, prev_user = self._request_queue.get_nowait()
@@ -606,7 +609,7 @@ def _parse_result(
606609

607610
return any_fail, failed_power
608611

609-
async def _cancel_tasks(self, tasks: Iterable["asyncio.Task[Any]"]) -> None:
612+
async def _cancel_tasks(self, tasks: Iterable[asyncio.Task[Any]]) -> None:
610613
"""Cancel given asyncio tasks and wait for them.
611614
612615
Args:

tests/test_microgrid/mock_api.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
all framework code, as API integration should be highly encapsulated.
99
"""
1010

11+
from __future__ import annotations
1112

1213
# pylint: disable=invalid-name,no-name-in-module,unused-import
1314
from concurrent import futures
@@ -59,7 +60,7 @@ class MockMicrogridServicer( # pylint: disable=too-many-public-methods
5960

6061
def __init__(
6162
self,
62-
components: Optional[List[Tuple[int, "ComponentCategory.V"]]] = None,
63+
components: Optional[List[Tuple[int, ComponentCategory.V]]] = None,
6364
connections: Optional[List[Tuple[int, int]]] = None,
6465
) -> None:
6566
"""Create a MockMicrogridServicer instance."""
@@ -76,7 +77,7 @@ def __init__(
7677
self._latest_discharge: Optional[PowerLevelParam] = None
7778

7879
def add_component(
79-
self, component_id: int, component_category: "ComponentCategory.V"
80+
self, component_id: int, component_category: ComponentCategory.V
8081
) -> None:
8182
"""Add a component to the mock service."""
8283
self._components.append(Component(id=component_id, category=component_category))
@@ -85,9 +86,7 @@ def add_connection(self, start: int, end: int) -> None:
8586
"""Add a connection to the mock service."""
8687
self._connections.append(Connection(start=start, end=end))
8788

88-
def set_components(
89-
self, components: List[Tuple[int, "ComponentCategory.V"]]
90-
) -> None:
89+
def set_components(self, components: List[Tuple[int, ComponentCategory.V]]) -> None:
9190
"""Set components to mock service, dropping existing."""
9291
self._components.clear()
9392
self._components.extend(

0 commit comments

Comments
 (0)