Skip to content

Commit 1a70a67

Browse files
Apply changes suggested by the tool pyupgrade
The tool `pyupgrade` was used to modernize the code base given that frequenz-SDK is already using python 3.11 as minimum version. The tool was mainly used to replace obsolete types. Just as a reference the tool was run with the following shell command: ```sh find ./src ./benchmarks ./docs ./examples \ ./tests -name '*.py' -exec pyupgrade --py311-plus {} \; ``` Also black and isort were both run to format the code base after running pyupgrade. Signed-off-by: Daniel Zullo <[email protected]>
1 parent ae1c2a0 commit 1a70a67

File tree

59 files changed

+450
-457
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

59 files changed

+450
-457
lines changed

benchmarks/power_distribution/power_distributor.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@
77
import csv
88
import random
99
import timeit
10+
from collections.abc import Coroutine
1011
from datetime import timedelta
11-
from typing import Any, Coroutine, Dict, List, Set # pylint: disable=unused-import
12+
from typing import Any, Dict, List, Set # pylint: disable=unused-import
1213

1314
from frequenz.channels import Broadcast
1415

@@ -32,7 +33,7 @@
3233
PORT = 61060
3334

3435

35-
async def send_requests(batteries: Set[int], request_num: int) -> List[Result]:
36+
async def send_requests(batteries: set[int], request_num: int) -> list[Result]:
3637
"""Send requests to the PowerDistributingActor and wait for the response.
3738
3839
Args:
@@ -47,7 +48,7 @@ async def send_requests(batteries: Set[int], request_num: int) -> List[Result]:
4748
"""
4849
battery_pool = microgrid.battery_pool(batteries)
4950
results_rx = battery_pool.power_distribution_results()
50-
result: List[Result] = []
51+
result: list[Result] = []
5152
for _ in range(request_num):
5253
await battery_pool.set_power(Power(float(random.randrange(100000, 1000000))))
5354
try:
@@ -61,7 +62,7 @@ async def send_requests(batteries: Set[int], request_num: int) -> List[Result]:
6162
return result
6263

6364

64-
def parse_result(result: List[List[Result]]) -> Dict[str, float]:
65+
def parse_result(result: list[list[Result]]) -> dict[str, float]:
6566
"""Parse result.
6667
6768
Args:
@@ -91,8 +92,8 @@ def parse_result(result: List[List[Result]]) -> Dict[str, float]:
9192

9293
async def run_test( # pylint: disable=too-many-locals
9394
num_requests: int,
94-
batteries: Set[int],
95-
) -> Dict[str, Any]:
95+
batteries: set[int],
96+
) -> dict[str, Any]:
9697
"""Run test.
9798
9899
Args:
@@ -112,7 +113,7 @@ async def run_test( # pylint: disable=too-many-locals
112113
requests_receiver=power_request_channel.new_receiver(),
113114
battery_status_sender=battery_status_channel.new_sender(),
114115
):
115-
tasks: List[Coroutine[Any, Any, List[Result]]] = []
116+
tasks: list[Coroutine[Any, Any, list[Result]]] = []
116117
tasks.append(send_requests(batteries, num_requests))
117118

118119
result = await asyncio.gather(*tasks)
@@ -133,7 +134,7 @@ async def run() -> None:
133134
HOST, PORT, ResamplerConfig(resampling_period=timedelta(seconds=1.0))
134135
)
135136

136-
all_batteries: Set[Component] = connection_manager.get().component_graph.components(
137+
all_batteries: set[Component] = connection_manager.get().component_graph.components(
137138
component_category={ComponentCategory.BATTERY}
138139
)
139140
batteries_ids = {c.component_id for c in all_batteries}

benchmarks/timeseries/benchmark_datasourcing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ async def consume(channel: Receiver[Any]) -> None:
131131
)
132132

133133

134-
def parse_args() -> Tuple[int, int, bool]:
134+
def parse_args() -> tuple[int, int, bool]:
135135
"""Parse the command line arguments.
136136
137137
Returns:

benchmarks/timeseries/benchmark_ringbuffer.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def test_slices(days: int, buffer: OrderedRingBuffer[Any], median: bool) -> None
6666
total += float(np.average(minutes))
6767

6868

69-
def test_29_days_list(num_runs: int) -> Dict[str, float]:
69+
def test_29_days_list(num_runs: int) -> dict[str, float]:
7070
"""Run the 29 day test on the list backend."""
7171
days = 29
7272
buffer = OrderedRingBuffer([0.0] * MINUTES_IN_29_DAYS, timedelta(minutes=1))
@@ -76,7 +76,7 @@ def test_29_days_list(num_runs: int) -> Dict[str, float]:
7676
return {"fill": fill_time, "test": test_time}
7777

7878

79-
def test_29_days_array(num_runs: int) -> Dict[str, float]:
79+
def test_29_days_array(num_runs: int) -> dict[str, float]:
8080
"""Run the 29 day test on the array backend."""
8181
days = 29
8282
buffer = OrderedRingBuffer(
@@ -91,7 +91,7 @@ def test_29_days_array(num_runs: int) -> Dict[str, float]:
9191
return {"fill": fill_time, "test": test_time}
9292

9393

94-
def test_29_days_slicing_list(num_runs: int) -> Dict[str, float]:
94+
def test_29_days_slicing_list(num_runs: int) -> dict[str, float]:
9595
"""Run slicing tests on list backend."""
9696
days = 29
9797
buffer = OrderedRingBuffer([0.0] * MINUTES_IN_29_DAYS, timedelta(minutes=1))
@@ -107,7 +107,7 @@ def test_29_days_slicing_list(num_runs: int) -> Dict[str, float]:
107107
return {"fill": fill_time, "median": median_test_time, "avg": avg_test_time}
108108

109109

110-
def test_29_days_slicing_array(num_runs: int) -> Dict[str, float]:
110+
def test_29_days_slicing_array(num_runs: int) -> dict[str, float]:
111111
"""Run slicing tests on array backend."""
112112
days = 29
113113
buffer = OrderedRingBuffer(

benchmarks/timeseries/periodic_feature_extractor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def _calculate_avg_window_py(
7979
feature_extractor: PeriodicFeatureExtractor,
8080
window: NDArray[np.float_],
8181
window_size: int,
82-
weights: List[float] | None = None,
82+
weights: list[float] | None = None,
8383
) -> NDArray[np.float_]:
8484
"""
8585
Plain python version of the average calculator.

benchmarks/timeseries/resampling.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33

44
"""Benchmark resampling."""
55

6+
from collections.abc import Sequence
67
from datetime import datetime, timedelta, timezone
78
from timeit import timeit
8-
from typing import Sequence
99

1010
from frequenz.sdk.timeseries import Sample
1111
from frequenz.sdk.timeseries._quantities import Quantity

examples/battery_pool.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ async def main() -> None:
3232
)
3333

3434
battery_pool = microgrid.battery_pool()
35-
receivers: Dict[str, Receiver[Any]] = {
35+
receivers: dict[str, Receiver[Any]] = {
3636
"soc": battery_pool.soc.new_receiver(maxsize=1),
3737
"capacity": battery_pool.capacity.new_receiver(maxsize=1),
3838
"power_bounds": battery_pool.power_bounds.new_receiver(maxsize=1),

src/frequenz/sdk/_internal/_singleton_meta.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
class SingletonMeta(type):
1111
"""This is a thread-safe implementation of Singleton."""
1212

13-
_instances: Dict[Any, type] = {}
13+
_instances: dict[Any, type] = {}
1414
"""The dictionary of instances of the singleton classes."""
1515

1616
_lock: Lock = Lock()

src/frequenz/sdk/actor/_channel_registry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def __init__(self, *, name: str) -> None:
2222
name: A unique name for the registry.
2323
"""
2424
self._name = name
25-
self._channels: Dict[str, Broadcast[Any]] = {}
25+
self._channels: dict[str, Broadcast[Any]] = {}
2626

2727
def new_sender(self, key: str) -> Sender[Any]:
2828
"""Get a sender to a dynamically created channel with the given key.

src/frequenz/sdk/actor/_data_sourcing/microgrid_api_source.py

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55

66
import asyncio
77
import logging
8-
from typing import Any, Callable, Dict, List, Optional, Tuple
8+
from collections.abc import Callable
9+
from typing import Any, Dict, List, Optional, Tuple
910

1011
from frequenz.channels import Receiver, Sender
1112

@@ -23,7 +24,7 @@
2324
from .._channel_registry import ChannelRegistry
2425
from ._component_metric_request import ComponentMetricRequest
2526

26-
_MeterDataMethods: Dict[ComponentMetricId, Callable[[MeterData], float]] = {
27+
_MeterDataMethods: dict[ComponentMetricId, Callable[[MeterData], float]] = {
2728
ComponentMetricId.ACTIVE_POWER: lambda msg: msg.active_power,
2829
ComponentMetricId.CURRENT_PHASE_1: lambda msg: msg.current_per_phase[0],
2930
ComponentMetricId.CURRENT_PHASE_2: lambda msg: msg.current_per_phase[1],
@@ -34,7 +35,7 @@
3435
ComponentMetricId.FREQUENCY: lambda msg: msg.frequency,
3536
}
3637

37-
_BatteryDataMethods: Dict[ComponentMetricId, Callable[[BatteryData], float]] = {
38+
_BatteryDataMethods: dict[ComponentMetricId, Callable[[BatteryData], float]] = {
3839
ComponentMetricId.SOC: lambda msg: msg.soc,
3940
ComponentMetricId.SOC_LOWER_BOUND: lambda msg: msg.soc_lower_bound,
4041
ComponentMetricId.SOC_UPPER_BOUND: lambda msg: msg.soc_upper_bound,
@@ -54,7 +55,7 @@
5455
ComponentMetricId.TEMPERATURE: lambda msg: msg.temperature,
5556
}
5657

57-
_InverterDataMethods: Dict[ComponentMetricId, Callable[[InverterData], float]] = {
58+
_InverterDataMethods: dict[ComponentMetricId, Callable[[InverterData], float]] = {
5859
ComponentMetricId.ACTIVE_POWER: lambda msg: msg.active_power,
5960
ComponentMetricId.ACTIVE_POWER_INCLUSION_LOWER_BOUND: lambda msg: (
6061
msg.active_power_inclusion_lower_bound
@@ -71,7 +72,7 @@
7172
ComponentMetricId.FREQUENCY: lambda msg: msg.frequency,
7273
}
7374

74-
_EVChargerDataMethods: Dict[ComponentMetricId, Callable[[EVChargerData], float]] = {
75+
_EVChargerDataMethods: dict[ComponentMetricId, Callable[[EVChargerData], float]] = {
7576
ComponentMetricId.ACTIVE_POWER: lambda msg: msg.active_power,
7677
ComponentMetricId.CURRENT_PHASE_1: lambda msg: msg.current_per_phase[0],
7778
ComponentMetricId.CURRENT_PHASE_2: lambda msg: msg.current_per_phase[1],
@@ -99,22 +100,20 @@ def __init__(
99100
registry: A channel registry. To be replaced by a singleton
100101
instance.
101102
"""
102-
self._comp_categories_cache: Dict[int, ComponentCategory] = {}
103+
self._comp_categories_cache: dict[int, ComponentCategory] = {}
103104

104-
self.comp_data_receivers: Dict[int, Receiver[Any]] = {}
105+
self.comp_data_receivers: dict[int, Receiver[Any]] = {}
105106
"""The dictionary of component IDs to data receivers."""
106107

107-
self.comp_data_tasks: Dict[int, asyncio.Task[None]] = {}
108+
self.comp_data_tasks: dict[int, asyncio.Task[None]] = {}
108109
"""The dictionary of component IDs to asyncio tasks."""
109110

110111
self._registry = registry
111-
self._req_streaming_metrics: Dict[
112-
int, Dict[ComponentMetricId, List[ComponentMetricRequest]]
112+
self._req_streaming_metrics: dict[
113+
int, dict[ComponentMetricId, list[ComponentMetricRequest]]
113114
] = {}
114115

115-
async def _get_component_category(
116-
self, comp_id: int
117-
) -> Optional[ComponentCategory]:
116+
async def _get_component_category(self, comp_id: int) -> ComponentCategory | None:
118117
"""Get the component category of the given component.
119118
120119
Args:
@@ -139,7 +138,7 @@ async def _get_component_category(
139138
async def _check_battery_request(
140139
self,
141140
comp_id: int,
142-
requests: Dict[ComponentMetricId, List[ComponentMetricRequest]],
141+
requests: dict[ComponentMetricId, list[ComponentMetricRequest]],
143142
) -> None:
144143
"""Check if the requests are valid Battery metrics.
145144
@@ -162,7 +161,7 @@ async def _check_battery_request(
162161
async def _check_ev_charger_request(
163162
self,
164163
comp_id: int,
165-
requests: Dict[ComponentMetricId, List[ComponentMetricRequest]],
164+
requests: dict[ComponentMetricId, list[ComponentMetricRequest]],
166165
) -> None:
167166
"""Check if the requests are valid EV Charger metrics.
168167
@@ -185,7 +184,7 @@ async def _check_ev_charger_request(
185184
async def _check_inverter_request(
186185
self,
187186
comp_id: int,
188-
requests: Dict[ComponentMetricId, List[ComponentMetricRequest]],
187+
requests: dict[ComponentMetricId, list[ComponentMetricRequest]],
189188
) -> None:
190189
"""Check if the requests are valid Inverter metrics.
191190
@@ -208,7 +207,7 @@ async def _check_inverter_request(
208207
async def _check_meter_request(
209208
self,
210209
comp_id: int,
211-
requests: Dict[ComponentMetricId, List[ComponentMetricRequest]],
210+
requests: dict[ComponentMetricId, list[ComponentMetricRequest]],
212211
) -> None:
213212
"""Check if the requests are valid Meter metrics.
214213
@@ -232,7 +231,7 @@ async def _check_requested_component_and_metrics(
232231
self,
233232
comp_id: int,
234233
category: ComponentCategory,
235-
requests: Dict[ComponentMetricId, List[ComponentMetricRequest]],
234+
requests: dict[ComponentMetricId, list[ComponentMetricRequest]],
236235
) -> None:
237236
"""Check if the requested component and metrics are valid.
238237
@@ -289,8 +288,8 @@ def _get_data_extraction_method(
289288
def _get_metric_senders(
290289
self,
291290
category: ComponentCategory,
292-
requests: Dict[ComponentMetricId, List[ComponentMetricRequest]],
293-
) -> List[Tuple[Callable[[Any], float], List[Sender[Sample[Quantity]]]]]:
291+
requests: dict[ComponentMetricId, list[ComponentMetricRequest]],
292+
) -> list[tuple[Callable[[Any], float], list[Sender[Sample[Quantity]]]]]:
294293
"""Get channel senders from the channel registry for each requested metric.
295294
296295
Args:

src/frequenz/sdk/actor/_run_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ async def run(*actors: Actor) -> None:
2828
actor.start()
2929

3030
# Wait until all actors are done
31-
pending_tasks = set(asyncio.create_task(a.wait(), name=str(a)) for a in actors)
31+
pending_tasks = {asyncio.create_task(a.wait(), name=str(a)) for a in actors}
3232
while pending_tasks:
3333
done_tasks, pending_tasks = await asyncio.wait(
3434
pending_tasks, return_when=asyncio.FIRST_COMPLETED

0 commit comments

Comments
 (0)