Skip to content

Commit 59bc299

Browse files
committed
pybricksdev: use Python 3.9+ generics
Replace deprecated typing Type/Dict/List/Tuple with built-in generics.
1 parent 96a6e86 commit 59bc299

File tree

9 files changed

+38
-39
lines changed

9 files changed

+38
-39
lines changed

pybricksdev/ble/lwp3/bytecodes.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@
1111
"""
1212

1313
from enum import IntEnum, IntFlag, unique
14-
from typing import Type, Union
14+
from typing import Union
1515

1616

17-
def _create_pseudo_member_(cls: Type[IntEnum], value: int) -> IntEnum:
17+
def _create_pseudo_member_(cls: type[IntEnum], value: int) -> IntEnum:
1818
"""
1919
Creates a new enum member at runtime for ``IntEnum``s.
2020
"""

pybricksdev/ble/lwp3/messages.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import abc
1414
import struct
1515
from enum import IntEnum
16-
from typing import Any, Dict, List, NamedTuple, Tuple, Type, Union, overload
16+
from typing import Any, NamedTuple, Union, overload
1717

1818
from pybricksdev.ble.lwp3.bytecodes import (
1919
MAX_NAME_SIZE,
@@ -861,7 +861,7 @@ def __repr__(self) -> str:
861861

862862

863863
class PortFormatSetupComboMessage(AbstractPortFormatSetupComboMessage):
864-
def __init__(self, port: PortID, modes_and_datasets: List[Tuple[int, int]]) -> None:
864+
def __init__(self, port: PortID, modes_and_datasets: list[tuple[int, int]]) -> None:
865865
super().__init__(
866866
5 + len(modes_and_datasets), port, PortInfoFormatSetupCommand.SET
867867
)
@@ -870,7 +870,7 @@ def __init__(self, port: PortID, modes_and_datasets: List[Tuple[int, int]]) -> N
870870
self._data[i] = ((mode & 0xF) << 4) | (dataset & 0xF)
871871

872872
@property
873-
def modes_and_datasets(self) -> List[Tuple[int, int]]:
873+
def modes_and_datasets(self) -> list[tuple[int, int]]:
874874
return [(x >> 4, x & 0xF) for x in self._data[5:]]
875875

876876
def __repr__(self) -> str:
@@ -923,8 +923,8 @@ def __init__(
923923
port: PortID,
924924
capabilities: ModeCapabilities,
925925
num_modes: int,
926-
input_modes: List[int],
927-
output_modes: List[int],
926+
input_modes: list[int],
927+
output_modes: list[int],
928928
) -> None:
929929
super().__init__(11, port, InfoKind.MODE_INFO)
930930

@@ -955,12 +955,12 @@ def num_modes(self) -> int:
955955
return self._data[6]
956956

957957
@property
958-
def input_modes(self) -> List[int]:
958+
def input_modes(self) -> list[int]:
959959
(flags,) = struct.unpack_from("<H", self._data, 7)
960960
return [n for n in range(16) if flags & (1 << n)]
961961

962962
@property
963-
def output_modes(self) -> List[int]:
963+
def output_modes(self) -> list[int]:
964964
(flags,) = struct.unpack_from("<H", self._data, 9)
965965
return [n for n in range(16) if flags & (1 << n)]
966966

@@ -972,7 +972,7 @@ class PortInfoCombosMessage(AbstractPortInfoMessage):
972972
def __init__(
973973
self,
974974
port: PortID,
975-
combos: List[List[int]],
975+
combos: list[list[int]],
976976
) -> None:
977977
super().__init__(5 + len(combos) * 2, port, InfoKind.COMBOS)
978978

@@ -988,7 +988,7 @@ def __init__(
988988
struct.pack_into(f"<{len(flags)}H", self._data, 5, *flags)
989989

990990
@property
991-
def combos(self) -> List[List[int]]:
991+
def combos(self) -> list[list[int]]:
992992
count = (len(self._data) - 5) // 2
993993
return [
994994
[m for m in range(16) if flags & (1 << m)]
@@ -1221,7 +1221,7 @@ def __init__(self, port: PortID, fmt: str, *values: Union[int, float]) -> None:
12211221
def port(self) -> PortID:
12221222
return PortID(self._data[3])
12231223

1224-
def unpack(self, fmt: str) -> Tuple[Union[int, float], ...]:
1224+
def unpack(self, fmt: str) -> tuple[Union[int, float], ...]:
12251225
return struct.unpack_from(fmt, self._data, 4)
12261226

12271227
def __repr__(self) -> str:
@@ -1232,7 +1232,7 @@ def __repr__(self) -> str:
12321232

12331233
class PortValueComboMessage(AbstractMessage):
12341234
def __init__(
1235-
self, port: PortID, modes: List[int], fmt: str, *values: Union[int, float]
1235+
self, port: PortID, modes: list[int], fmt: str, *values: Union[int, float]
12361236
) -> None:
12371237
super().__init__(6 + struct.calcsize(fmt), MessageKind.PORT_VALUE_COMBO)
12381238

@@ -1249,11 +1249,11 @@ def port(self) -> PortID:
12491249
return PortID(self._data[3])
12501250

12511251
@property
1252-
def modes(self) -> List[int]:
1252+
def modes(self) -> list[int]:
12531253
(flags,) = struct.unpack_from("<H", self._data, 4)
12541254
return [m for m in range(16) if flags & (1 << m)]
12551255

1256-
def unpack(self, fmt: str) -> Tuple[Union[int, float], ...]:
1256+
def unpack(self, fmt: str) -> tuple[Union[int, float], ...]:
12571257
return struct.unpack_from(fmt, self._data, 6)
12581258

12591259
def __repr__(self) -> str:
@@ -1294,7 +1294,7 @@ def __init__(
12941294
port: PortID,
12951295
combo: int,
12961296
multi_update: bool,
1297-
modes_and_datasets: List[int],
1297+
modes_and_datasets: list[int],
12981298
) -> None:
12991299
super().__init__(7, MessageKind.PORT_INPUT_FMT_COMBO)
13001300

@@ -1321,7 +1321,7 @@ def multi_update(self) -> bool:
13211321
return bool(self._data[4] & 0x80)
13221322

13231323
@property
1324-
def modes_and_datasets(self) -> List[int]:
1324+
def modes_and_datasets(self) -> list[int]:
13251325
(flags,) = struct.unpack_from("<H", self._data, 5)
13261326
return [m for m in range(16) if flags & (1 << m)]
13271327

@@ -1467,7 +1467,7 @@ def __init__(
14671467
def mode(self) -> int:
14681468
return self._data[6]
14691469

1470-
def unpack(self, fmt: str) -> Tuple[Union[int, float], ...]:
1470+
def unpack(self, fmt: str) -> tuple[Union[int, float], ...]:
14711471
return struct.unpack_from(fmt, self._data, 7)
14721472

14731473
def __repr__(self) -> str:
@@ -1577,7 +1577,7 @@ class _Lookup(NamedTuple):
15771577
index: int
15781578
"""The index of the bytecode that determines the type."""
15791579

1580-
value: Union[Dict[IntEnum, Type[AbstractMessage]], Dict[IntEnum, "_Lookup"]]
1580+
value: Union[dict[IntEnum, type[AbstractMessage]], dict[IntEnum, "_Lookup"]]
15811581
"""
15821582
A dictionary mapping a bytecode to the cooresponding Python type if the type can be determined or
15831583
a dictionary mapping a bytecode to another lookup if more discrimination is required.

pybricksdev/ble/pybricks.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
from enum import IntEnum, IntFlag
2323
from struct import unpack
24-
from typing import Literal, Tuple
24+
from typing import Literal
2525

2626
import semver
2727

@@ -351,7 +351,7 @@ class UserProgramId(IntEnum):
351351
"""
352352

353353

354-
def unpack_hub_capabilities(data: bytes) -> Tuple[int, HubCapabilityFlag, int, int]:
354+
def unpack_hub_capabilities(data: bytes) -> tuple[int, HubCapabilityFlag, int, int]:
355355
"""
356356
Unpacks the value read from the hub capabilities characteristic.
357357
@@ -373,7 +373,7 @@ def unpack_hub_capabilities(data: bytes) -> Tuple[int, HubCapabilityFlag, int, i
373373
return max_char_size, HubCapabilityFlag(flags), max_user_prog_size, num_of_slots
374374

375375

376-
def unpack_hub_capabilities_v15(data: bytes) -> Tuple[int, HubCapabilityFlag, int, int]:
376+
def unpack_hub_capabilities_v15(data: bytes) -> tuple[int, HubCapabilityFlag, int, int]:
377377
"""
378378
Unpacks the value read from the hub capabilities characteristic. (Pybricks protocol v1.5)
379379
@@ -459,7 +459,7 @@ def short_uuid(uuid: str) -> int:
459459
"""
460460

461461

462-
def unpack_pnp_id(data: bytes) -> Tuple[Literal["BT", "USB"], int, int, int]:
462+
def unpack_pnp_id(data: bytes) -> tuple[Literal["BT", "USB"], int, int, int]:
463463
"""
464464
Unpacks raw data from the PnP ID characteristic.
465465

pybricksdev/cli/flash.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import sys
99
import zlib
1010
from tempfile import NamedTemporaryFile
11-
from typing import BinaryIO, Dict
11+
from typing import BinaryIO
1212

1313
from bleak import BleakClient, BleakScanner
1414
from bleak.backends.device import BLEDevice
@@ -273,7 +273,7 @@ async def flash_ble(hub_kind: HubKind, firmware: bytes, metadata: dict):
273273
# as return value from find_device_by_filter()
274274
# https://github.com/hbldh/bleak/issues/1277
275275

276-
device_adv_map: Dict[str, AdvertisementData] = {}
276+
device_adv_map: dict[str, AdvertisementData] = {}
277277

278278
def map_and_match(device: BLEDevice, adv: AdvertisementData):
279279
# capture the adv data for later use

pybricksdev/compile.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import logging
66
import os
77
from modulefinder import ModuleFinder
8-
from typing import List, Tuple, Union
8+
from typing import Union
99

1010
import mpy_cross_v5
1111
import mpy_cross_v6
@@ -81,7 +81,7 @@ async def compile_file(
8181
return mpy
8282

8383

84-
async def compile_multi_file(path: str, abi: Union[int, Tuple[int, int]]):
84+
async def compile_multi_file(path: str, abi: Union[int, tuple[int, int]]):
8585
"""Compiles a Python file and its dependencies with ``mpy-cross``.
8686
8787
On the hub, all dependencies behave as independent modules. Any (leading)
@@ -134,7 +134,7 @@ async def compile_multi_file(path: str, abi: Union[int, Tuple[int, int]]):
134134
logger.debug("missing modules: %r", finder.any_missing())
135135

136136
# Get a data blob with all scripts.
137-
parts: List[bytes] = []
137+
parts: list[bytes] = []
138138

139139
abi_major, abi_minor = (abi, None) if isinstance(abi, int) else abi
140140

pybricksdev/connections/ev3.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import enum
66
import itertools
77
import struct
8-
from typing import Callable, Tuple
8+
from typing import Callable
99

1010
import hid
1111

@@ -244,7 +244,7 @@ async def get_checksum(self, address: int, size: int) -> int:
244244
None, self.get_checksum_sync, address, size
245245
)
246246

247-
def get_version_sync(self) -> Tuple[int, int]:
247+
def get_version_sync(self) -> tuple[int, int]:
248248
"""
249249
Blocking version of :meth:`get_version`.
250250
"""
@@ -257,7 +257,7 @@ def get_version_sync(self) -> Tuple[int, int]:
257257
payload = self._receive_reply(Command.GET_VERSION, num, force_length=13)
258258
return struct.unpack("<II", payload)
259259

260-
async def get_version(self) -> Tuple[int, int]:
260+
async def get_version(self) -> tuple[int, int]:
261261
"""
262262
Gets the bootloader firmware version and the hardware version.
263263

pybricksdev/connections/pybricks.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import logging
77
import os
88
import struct
9-
from typing import Awaitable, Callable, List, TypeVar
9+
from typing import Awaitable, Callable, TypeVar
1010

1111
import reactivex.operators as op
1212
import semver
@@ -152,7 +152,7 @@ def __init__(self):
152152
# REVISIT: It would be better to be able to subscribe to output instead
153153
# of always capturing it even if it is not used. This is currently
154154
# used in motor test code in pybricks-micropython.
155-
self.output: List[bytes] = []
155+
self.output: list[bytes] = []
156156
"""
157157
Contains lines printed to stdout of the hub as a a list of bytes.
158158

pybricksdev/firmware.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import struct
1212
import sys
1313
import zipfile
14-
from typing import BinaryIO, List, Literal, Tuple, TypedDict, Union
14+
from typing import BinaryIO, Literal, TypedDict, Union
1515

1616
if sys.version_info < (3, 10):
1717
from typing_extensions import TypeGuard
@@ -33,7 +33,7 @@ class FirmwareMetadataV100(
3333
"device-id": Literal[0x40, 0x41, 0x80, 0x81],
3434
"checksum-type": Literal["sum", "crc32"],
3535
"mpy-abi-version": int,
36-
"mpy-cross-options": List[str],
36+
"mpy-cross-options": list[str],
3737
"user-mpy-offset": int,
3838
"max-firmware-size": int,
3939
},
@@ -234,7 +234,7 @@ async def _create_firmware_v2(
234234

235235
async def create_firmware_blob(
236236
firmware_zip: Union[str, os.PathLike, BinaryIO], name: str | None = None
237-
) -> Tuple[bytes, AnyFirmwareMetadata, str]:
237+
) -> tuple[bytes, AnyFirmwareMetadata, str]:
238238
"""Creates a firmware blob from base firmware and an optional custom name.
239239
240240
.. note:: The firmware.zip file must contain the following files::

pybricksdev/flash.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import platform
88
import struct
99
from collections import namedtuple
10-
from typing import Dict, List, Tuple
1110

1211
from tqdm.auto import tqdm
1312
from tqdm.contrib.logging import logging_redirect_tqdm
@@ -20,7 +19,7 @@
2019

2120

2221
# NAME, PAYLOAD_SIZE requirement
23-
HUB_INFO: Dict[HubKind, Tuple[str, int]] = {
22+
HUB_INFO: dict[HubKind, tuple[str, int]] = {
2423
HubKind.BOOST: ("Move Hub", 14),
2524
HubKind.CITY: ("City Hub", 32),
2625
HubKind.TECHNIC: ("Technic Hub", 32),
@@ -34,7 +33,7 @@ def __init__(
3433
self,
3534
command: BootloaderCommand,
3635
name: str,
37-
request_format: List[str],
36+
request_format: list[str],
3837
data_format: str,
3938
request_reply: bool = True,
4039
write_with_response: bool = True,

0 commit comments

Comments
 (0)