Skip to content

Commit 80c48d3

Browse files
committed
improve types
1 parent 5141942 commit 80c48d3

File tree

10 files changed

+40
-27
lines changed

10 files changed

+40
-27
lines changed

examples/custom_msg.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,10 @@ class CustomModbusResponse(ModbusPDU):
4343
function_code = 55
4444
rtu_byte_count_pos = 2
4545

46-
def __init__(self, values=None, device_id=1, transaction=0):
46+
def __init__(self, values: list[int] | None = None, device_id=1, transaction=0):
4747
"""Initialize."""
4848
super().__init__(dev_id=device_id, transaction_id=transaction)
49-
self.values = values or []
49+
self.values: list[int] = values or []
5050

5151
def encode(self):
5252
"""Encode response pdu.

examples/server_async.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def setup_server(description=None, context=None, cmdline=None):
8585
elif args.store == "sparse": # pragma: no cover
8686
# Continuing, or use a sparse DataBlock which can have gaps
8787
datablock = lambda : ModbusSparseDataBlock({0x00: 0, 0x05: 1}) # pylint: disable=unnecessary-lambda-assignment
88-
elif args.store == "factory": # pragma: no cover
88+
elif args.store == "factory" or True: # pragma: no cover # pylint: disable=condition-evals-to-constant
8989
# Alternately, use the factory methods to initialize the DataBlocks
9090
# or simply do not pass them to have them initialized to 0x00 on the
9191
# full address range::
@@ -98,15 +98,15 @@ def setup_server(description=None, context=None, cmdline=None):
9898
# (broadcast mode).
9999
# However, this can be overloaded by setting the single flag to False and
100100
# then supplying a dictionary of device id to context mapping::
101-
context = {}
102-
103-
for device_id in range(args.device_ids):
104-
context[device_id] = ModbusDeviceContext(
101+
context = {
102+
device_id : ModbusDeviceContext(
105103
di=datablock(),
106104
co=datablock(),
107105
hr=datablock(),
108106
ir=datablock(),
109107
)
108+
for device_id in range(args.device_ids)
109+
}
110110

111111
single = False
112112
else:

pymodbus/client/mixin.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -760,9 +760,10 @@ def convert_to_registers( # noqa: C901
760760
if data_type == cls.DATATYPE.BITS:
761761
if not isinstance(value, list):
762762
raise TypeError(f"Value should be list of bool but is {type(value)}.")
763+
value = cast(list[bool], value)
763764
if (missing := len(value) % 16):
764765
value = value + [False] * (16 - missing)
765-
byte_list = pack_bitstring(cast(list[bool], value))
766+
byte_list = pack_bitstring(value)
766767
elif data_type == cls.DATATYPE.STRING:
767768
if not isinstance(value, str):
768769
raise TypeError(f"Value should be string but is {type(value)}.")

pymodbus/datastore/context.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ def __init__(self, devices=None, single=True):
161161
:param single: Set to true to treat this as a single context
162162
"""
163163
self.single = single
164-
self._devices = devices or {}
164+
self._devices: dict = devices or {}
165165
if self.single:
166166
self._devices = {0: self._devices}
167167

pymodbus/pdu/device.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def __iter__(self):
9797
"""
9898
return iter(self.stat_data.items())
9999

100-
def reset(self):
100+
def reset(self) -> None:
101101
"""Clear all of the modbus plus statistics."""
102102
for key in self.stat_data:
103103
self.stat_data[key] = [0x00] * len(self.stat_data[key])
@@ -109,14 +109,14 @@ def summary(self):
109109
"""
110110
return iter(self.stat_data.values())
111111

112-
def encode(self):
112+
def encode(self) -> list[int]:
113113
"""Return a summary of the modbus plus statistics.
114114
115-
:returns: 54 16-bit words representing the status
115+
:returns: An iterator over lists of 8-bit integers representing each statistic
116116
"""
117-
total, values = [], sum(self.stat_data.values(), []) # noqa: RUF017
118-
for i in range(0, len(values), 2):
119-
total.append((values[i] << 8) | values[i + 1])
117+
values = [v for sublist in self.stat_data.values() for v in sublist]
118+
total = [(values[i] << 8) | values[i + 1]
119+
for i in range(0, len(values), 2)]
120120
return total
121121

122122

@@ -446,6 +446,8 @@ class ModbusControlBlock:
446446
_plus = ModbusPlusStatistics()
447447
_events: list[ModbusEvent] = []
448448

449+
_inst: ModbusControlBlock | None = None
450+
449451
# -------------------------------------------------------------------------#
450452
# Magic
451453
# -------------------------------------------------------------------------#
@@ -465,7 +467,7 @@ def __iter__(self):
465467

466468
def __new__(cls):
467469
"""Create a new instance."""
468-
if "_inst" not in vars(cls):
470+
if cls._inst is None:
469471
cls._inst = object.__new__(cls)
470472
return cls._inst
471473

pymodbus/pdu/file_message.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,8 @@ def encode(self) -> bytes:
105105

106106
def decode(self, data: bytes) -> None:
107107
"""Decode the response."""
108-
count, self.records = 1, []
108+
count = 1
109+
self.records.clear()
109110
byte_count = int(data[0])
110111
while count < byte_count:
111112
calc_length, _ = struct.unpack(
@@ -151,7 +152,8 @@ def encode(self) -> bytes:
151152
def decode(self, data: bytes) -> None:
152153
"""Decode the incoming request."""
153154
byte_count = int(data[0])
154-
count, self.records = 1, []
155+
count = 1
156+
self.records.clear()
155157
while count < byte_count:
156158
decoded = struct.unpack(">BHHH", data[count : count + 7])
157159
calc_length = decoded[3] * 2
@@ -204,7 +206,8 @@ def encode(self) -> bytes:
204206

205207
def decode(self, data: bytes) -> None:
206208
"""Decode the incoming request."""
207-
count, self.records = 1, []
209+
count = 1
210+
self.records.clear()
208211
byte_count = int(data[0])
209212
while count < byte_count:
210213
decoded = struct.unpack(">BHHH", data[count : count + 7])

pymodbus/pdu/mei_message.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from __future__ import annotations
33

44
import struct
5+
from typing import Any
56

67
from pymodbus.constants import DeviceInformation, ExcCodes, MoreData
78
from pymodbus.datastore import ModbusDeviceContext
@@ -96,7 +97,7 @@ def __init__(self, read_code: int | None = None, information: dict | None = None
9697
"""Initialize a new instance."""
9798
super().__init__(transaction_id=transaction_id, dev_id=dev_id)
9899
self.read_code = read_code or DeviceInformation.BASIC
99-
self.information = information or {}
100+
self.information: dict[int, Any] = information or {}
100101
self.number_of_objects = 0
101102
self.conformity = 0x83 # I support everything right now
102103
self.next_object_id = 0x00
@@ -150,7 +151,8 @@ def decode(self, data: bytes) -> None:
150151
self.sub_function_code, self.read_code = params[0:2]
151152
self.conformity, self.more_follows = params[2:4]
152153
self.next_object_id, self.number_of_objects = params[4:6]
153-
self.information, count = {}, 6 # skip the header information
154+
count = 6 # skip the header information
155+
self.information.clear()
154156

155157
while count < len(data):
156158
object_id, object_length = struct.unpack(">BB", data[count : count + 2])

pymodbus/server/simulator/http_server.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import importlib
88
import json
99
import os
10+
from typing import TYPE_CHECKING
1011

1112

1213
with contextlib.suppress(ImportError):
@@ -25,6 +26,9 @@
2526
)
2627

2728

29+
if TYPE_CHECKING:
30+
from aiohttp import web
31+
2832
MAX_FILTER = 1000
2933

3034
RESPONSE_INACTIVE = -1
@@ -137,7 +141,7 @@ def __init__(
137141
del server["port"]
138142
device = setup["device_list"][modbus_device]
139143
self.datastore_context = ModbusSimulatorContext(
140-
device, custom_actions_dict or {}
144+
device, custom_actions_dict or None
141145
)
142146
datastore = None
143147
if "device_id" in server:
@@ -251,7 +255,7 @@ async def stop(self):
251255
self.serving.set_result(True)
252256
await asyncio.sleep(0)
253257

254-
async def handle_html_static(self, request): # pragma: no cover
258+
async def handle_html_static(self, request: web.Request): # pragma: no cover
255259
"""Handle static html."""
256260
if not (page := request.path[1:]):
257261
page = "index.html"
@@ -264,7 +268,7 @@ async def handle_html_static(self, request): # pragma: no cover
264268
except (FileNotFoundError, IsADirectoryError) as exc:
265269
raise web.HTTPNotFound(reason="File not found") from exc
266270

267-
async def handle_html(self, request): # pragma: no cover
271+
async def handle_html(self, request: web.Request): # pragma: no cover
268272
"""Handle html."""
269273
page_type = request.path.split("/")[-1]
270274
params = dict(request.query)
@@ -280,7 +284,7 @@ async def handle_html(self, request): # pragma: no cover
280284
new_page = self.generator_html[page_type][1](params, html)
281285
return web.Response(text=new_page, content_type="text/html")
282286

283-
async def handle_json(self, request):
287+
async def handle_json(self, request: web.Request):
284288
"""Handle api registers."""
285289
command = request.path.split("/")[-1]
286290
params = await request.json()

pymodbus/transport/transport.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ def generate_ssl(
126126
)
127127
return new_sslctx
128128

129-
def copy(self) -> CommParams:
129+
def copy(self: CommParams) -> CommParams:
130130
"""Create a copy."""
131131
return dataclasses.replace(self)
132132

pyproject.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ skip = "./build,./doc/source/_static,venv,.venv,.git,htmlcov,CHANGELOG.rst,.*_ca
250250
ignore-words-list = "asend"
251251

252252
[tool.ruff]
253-
target-version="py39"
253+
target-version="py310"
254254
extend-exclude = [
255255
"build",
256256
"doc",
@@ -312,3 +312,4 @@ line-ending = "auto"
312312

313313
[tool.pyright]
314314
disableBytesTypePromotions = false
315+
typeCheckingMode = "standard"

0 commit comments

Comments
 (0)