Skip to content

Commit 149eb2b

Browse files
committed
python: fix type annotations
1 parent ce933db commit 149eb2b

File tree

12 files changed

+252
-188
lines changed

12 files changed

+252
-188
lines changed

.vscode/settings.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"editor.formatOnSave": true,
33
"[python]": {
4-
"editor.defaultFormatter": "ms-python.black-formatter"
4+
"editor.defaultFormatter": "charliermarsh.ruff"
55
},
66

77
"python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python",

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file.
44

55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
66

7+
## [2.5.2] - 2024-12-05
8+
9+
- python: bump bump dependencies
10+
- python: fix type annotations
11+
712
## [2.5.1] - 2024-09-27
813

914
- Python timeout API improvements

python/comsrv/__init__.py

Lines changed: 56 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
from typing import Any, List, Optional, Tuple, Union
1111

1212
from aiohttp import ClientSession, ClientTimeout # type: ignore
13-
from broadcast_wsrpc.client import Client, JsonDict, JsonType
13+
from broadcast_wsrpc.client import Client
14+
from broadcast_wsrpc.json import JsonObject, JsonType
1415

1516

1617
class ComSrvError(Exception):
@@ -20,9 +21,11 @@ class ComSrvError(Exception):
2021
"""
2122

2223
@classmethod
23-
def parse(cls, data: JsonDict) -> "ComSrvError":
24+
def parse(cls, data: JsonObject) -> "ComSrvError":
2425
if "Protocol" in data:
25-
return ProtocolError.parse(data["Protocol"])
26+
protocol = data["Protocol"]
27+
assert isinstance(protocol, dict)
28+
return ProtocolError.parse(protocol)
2629
if "Transport" in data:
2730
return TransportError(data["Transport"])
2831
if "Argument" in data:
@@ -32,9 +35,11 @@ def parse(cls, data: JsonDict) -> "ComSrvError":
3235
return ComSrvError(data)
3336

3437
@classmethod
35-
def check_raise(cls, result: JsonDict) -> None:
38+
def check_raise(cls, result: JsonObject) -> None:
3639
if "Error" in result:
37-
raise ComSrvError.parse(result["Error"])
40+
err = result["Error"]
41+
assert isinstance(err, dict)
42+
raise ComSrvError.parse(err)
3843

3944

4045
class ArgumentError(ComSrvError):
@@ -60,12 +65,15 @@ class ProtocolError(ComSrvError):
6065
"""
6166

6267
@classmethod
63-
def parse(cls, data: JsonDict) -> "ProtocolError":
68+
def parse(cls, data: JsonObject) -> "ProtocolError":
6469
if "Timeout" in data:
6570
return ProtocolTimeoutError()
6671
if "Other" in data:
72+
other = data["Other"]
73+
assert isinstance(other, dict)
6774
return ProtocolError(
68-
data["Other"]["description"], data["Other"]["backtrace"]
75+
other["description"],
76+
other["backtrace"],
6977
)
7078
return ProtocolError(data)
7179

@@ -156,7 +164,7 @@ class Rpc(object):
156164
Base class for RPC service implementations.
157165
"""
158166

159-
async def get(self, request: JsonType, timeout: float) -> JsonDict:
167+
async def get(self, request: JsonType, timeout: float) -> JsonObject:
160168
"""
161169
Send a request and wait for the response, but for at most `timeout`.
162170
"""
@@ -184,7 +192,7 @@ def __init__(self, url: str | None = None) -> None:
184192
url = get_default_http_url()
185193
self._url = url
186194

187-
async def get(self, request: JsonType, timeout: float) -> JsonDict:
195+
async def get(self, request: JsonType, timeout: float) -> JsonObject:
188196
data = json.dumps(request).encode()
189197
to = ClientTimeout(total=None, sock_connect=timeout, sock_read=timeout)
190198
async with ClientSession(timeout=to) as session:
@@ -216,9 +224,9 @@ def __init__(self, url: str | None = None, **kw: Any) -> None:
216224
self._kw = kw
217225
self._client = Client()
218226

219-
async def get(self, data: JsonType, timeout: float) -> JsonDict:
227+
async def get(self, request: JsonType, timeout: float) -> JsonObject:
220228
await self.connect(self._url)
221-
ret = await self._client.request(data, timeout)
229+
ret = await self._client.request(request, timeout)
222230
if not isinstance(ret, dict):
223231
raise ComSrvError(f"Got wrong JSON type. Expected dict, got {type(ret)}")
224232
return ret
@@ -248,7 +256,7 @@ class Address(object):
248256
def to_json(self) -> JsonType:
249257
raise NotImplementedError
250258

251-
def to_json_enum(self) -> JsonDict:
259+
def to_json_enum(self) -> JsonObject:
252260
return {self.enum_name: self.to_json()}
253261

254262
@property
@@ -271,7 +279,7 @@ def to_json(self) -> JsonType:
271279
raise NotImplementedError
272280

273281

274-
def duration_to_json(time_in_seconds: float) -> JsonDict:
282+
def duration_to_json(time_in_seconds: float) -> JsonObject:
275283
"""
276284
Serialize a duration in seconds to a RPC `Duration` object.
277285
"""
@@ -294,7 +302,7 @@ def __init__(self, address: Address, rpc: Optional[Rpc] = None):
294302
rpc = Rpc.make_default()
295303
self._lock_time = 1.0
296304
self._address = address
297-
self._lock = None
305+
self._lock: str | None = None
298306
self._rpc = rpc
299307
self._timeout = BasePipe.DEFAULT_TIMEOUT
300308

@@ -357,14 +365,18 @@ async def lock(self, timeout: Union[float, None] = None) -> "BasePipe":
357365
},
358366
timeout=lock_time,
359367
)
360-
self._lock = reply["Locked"]["lock_id"]
368+
lock = reply["Locked"]
369+
assert isinstance(lock, dict) and "lock_id" in lock
370+
lock_id = lock["lock_id"]
371+
assert isinstance(lock_id, str)
372+
self._lock = lock_id
361373
return self
362374

363375
@property
364376
def lock_id(self) -> str | None:
365377
return self._lock
366378

367-
async def get(self, data: JsonType, timeout: float | None = None) -> JsonDict:
379+
async def get(self, data: JsonType, timeout: float | None = None) -> JsonObject:
368380
"""
369381
Send a request and return the corresponding response but wait for at most `timeout`
370382
seconds.
@@ -479,7 +491,7 @@ def timeout(self, value: float) -> None:
479491
def rpc(self) -> Rpc:
480492
return self._rpc
481493

482-
async def get(self, data: JsonType, timeout: float | None = None) -> JsonDict:
494+
async def get(self, data: JsonType, timeout: float | None = None) -> JsonObject:
483495
if timeout is None:
484496
timeout = self._timeout
485497
return await self._rpc.get(data, timeout)
@@ -491,11 +503,15 @@ async def drop(self, addr: Address, lock: str | None = None) -> None:
491503
async def get_version(self) -> Tuple[int, int, int]:
492504
result = await self.get({"Version": None})
493505
ComSrvError.check_raise(result)
494-
return (
495-
result["Version"]["major"],
496-
result["Version"]["minor"],
497-
result["Version"]["build"],
506+
version = result["Version"]
507+
assert isinstance(version, dict)
508+
major = version["major"]
509+
minor = version["minor"]
510+
build = version["build"]
511+
assert (
512+
isinstance(major, int) and isinstance(minor, int) and isinstance(build, int)
498513
)
514+
return (major, minor, build)
499515

500516
async def drop_all(self) -> None:
501517
result = await self.get({"DropAll": None})
@@ -505,10 +521,12 @@ async def shutdown(self) -> None:
505521
result = await self.get({"Shutdown": None})
506522
ComSrvError.check_raise(result)
507523

508-
async def list_connected_instruments(self) -> List[JsonDict]:
524+
async def list_connected_instruments(self) -> List[JsonObject]:
509525
result = await self.get({"ListConnectedInstruments": None})
510526
ComSrvError.check_raise(result)
511-
return result["Instruments"]
527+
instruments = result["Instruments"]
528+
assert isinstance(instruments, list)
529+
return instruments # type: ignore
512530

513531
async def list_hid_devices(self) -> List[HidDeviceInfo]:
514532
from .hid import enumerate_hid_devices
@@ -518,15 +536,19 @@ async def list_hid_devices(self) -> List[HidDeviceInfo]:
518536
async def list_serial_ports(self) -> List[str]:
519537
result = await self.get({"ListSerialPorts": None})
520538
ComSrvError.check_raise(result)
521-
return result["SerialPorts"]
539+
serial_ports = result["SerialPorts"]
540+
assert isinstance(serial_ports, list)
541+
return serial_ports # type: ignore
522542

523543
async def list_ftdis(self) -> List[FtdiDeviceInfo]:
524544
result = await self.get({"ListFtdiDevices": None})
525545
ComSrvError.check_raise(result)
526546
ret = []
527-
for x in result["FtdiDevices"]:
528-
ret.append(FtdiDeviceInfo(**x))
529-
return ret
547+
ftdi_devices = result["FtdiDevices"]
548+
assert isinstance(ftdi_devices, list)
549+
for x in ftdi_devices:
550+
ret.append(FtdiDeviceInfo(**x)) # type: ignore
551+
return ret # type: ignore
530552

531553
async def list_can_devices(self) -> List[CanDevice]:
532554
result = await self.get(
@@ -536,13 +558,15 @@ async def list_can_devices(self) -> List[CanDevice]:
536558
)
537559
ComSrvError.check_raise(result)
538560
ret = []
539-
for x in result["CanDevices"]:
540-
if x["driver_type"] == "SocketCAN":
561+
can_devices = result["CanDevices"]
562+
assert isinstance(can_devices, list)
563+
for x in can_devices:
564+
if x["driver_type"] == "SocketCAN": # type: ignore
541565
driver_type = CanDriverType.SOCKETCAN
542-
elif x["driver_type"] == "PCAN":
566+
elif x["driver_type"] == "PCAN": # type: ignore
543567
driver_type = CanDriverType.PCAN
544-
ret.append(CanDevice(x["interface_name"], driver_type=driver_type))
545-
return ret
568+
ret.append(CanDevice(x["interface_name"], driver_type=driver_type)) # type: ignore
569+
return ret # type: ignore
546570

547571

548572
from .bytestream import ( # noqa: E402

0 commit comments

Comments
 (0)