Skip to content

Commit 2416b7d

Browse files
committed
Convert type hints to PEP585
1 parent 3e03c51 commit 2416b7d

File tree

6 files changed

+32
-27
lines changed

6 files changed

+32
-27
lines changed

examples/contrib/explain.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@
33
44
Created on 7/19/2023 to support Python 3.8 to 3.11 on macOS, Ubuntu, or Windows.
55
"""
6+
from __future__ import annotations
67

78
import contextlib
89
import os
910
import shutil
1011
import tempfile
1112
from dataclasses import dataclass
1213
from html.parser import HTMLParser
13-
from typing import List, Optional, Tuple, Union
1414
from urllib import request
1515
from urllib.error import HTTPError
1616

@@ -27,10 +27,10 @@ class ParsedModbusResult: # pylint: disable=too-many-instance-attributes
2727
unit_id: int
2828
func_code: int
2929
is_receive: bool
30-
zero_index_reg: Optional[int] = None
31-
quantity: Optional[int] = None
32-
byte_count: Optional[int] = None
33-
registers: Optional[List[int]] = None
30+
zero_index_reg: int | None = None
31+
quantity: int | None = None
32+
byte_count: int | None = None
33+
registers: list[int] | None = None
3434

3535
def summarize(self) -> dict:
3636
"""Get a summary representation for readability."""
@@ -46,7 +46,7 @@ def explain_with_rapid_scada(
4646
packet: str,
4747
is_modbus_tcp: bool = True,
4848
is_receive: bool = False,
49-
timeout: Union[float, Tuple[float, float], None] = 15.0,
49+
timeout: float | tuple[float, float] | None = 15.0,
5050
) -> ParsedModbusResult:
5151
"""
5252
Explain a Modbus packet using https://rapidscada.net/modbus/.
@@ -69,7 +69,7 @@ def __init__(self, *, convert_charrefs=True):
6969
self._data = []
7070

7171
@property
72-
def data(self) -> List[str]:
72+
def data(self) -> list[str]:
7373
return self._data
7474

7575
def handle_data(self, data: str) -> None:
@@ -101,7 +101,7 @@ def handle_data(self, data: str) -> None:
101101
parser.feed(response_data)
102102

103103
# pylint: disable-next=dangerous-default-value
104-
def get_next_field(prior_field: str, data: List[str] = parser.data) -> str:
104+
def get_next_field(prior_field: str, data: list[str] = parser.data) -> str:
105105
return data[data.index(prior_field) + 1]
106106

107107
def parse_next_field(prior_field: str, split_index: int = 0) -> int:
@@ -114,7 +114,7 @@ def parse_next_field(prior_field: str, split_index: int = 0) -> int:
114114
"func_code": parse_next_field("Function code"),
115115
"is_receive": is_receive,
116116
}
117-
is_receive_fn_code: Tuple[bool, int] = is_receive, base_result_data["func_code"]
117+
is_receive_fn_code: tuple[bool, int] = is_receive, base_result_data["func_code"]
118118
if is_receive_fn_code in [(False, 0x03), (True, 0x10)]:
119119
return ParsedModbusResult(
120120
**base_result_data,
@@ -136,7 +136,7 @@ def parse_next_field(prior_field: str, split_index: int = 0) -> int:
136136
)
137137

138138

139-
def annotate_pymodbus_logs(file: Union[str, os.PathLike]) -> None:
139+
def annotate_pymodbus_logs(file: str | os.PathLike) -> None:
140140
"""Annotate a pymodbus log file in-place with explanations."""
141141
with open(file, encoding="utf-8") as in_file, tempfile.NamedTemporaryFile(
142142
mode="w", encoding="utf-8", delete=False

pymodbus/framer/base.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
"""Framer start."""
22
# pylint: disable=missing-type-doc
3-
from typing import Any, Dict, Union
3+
from __future__ import annotations
4+
5+
from typing import Any
46

57
from pymodbus.factory import ClientDecoder, ServerDecoder
68
from pymodbus.logging import Log
@@ -24,7 +26,7 @@ class ModbusFramer:
2426

2527
def __init__(
2628
self,
27-
decoder: Union[ClientDecoder, ServerDecoder],
29+
decoder: ClientDecoder | ServerDecoder,
2830
client=None,
2931
) -> None:
3032
"""Initialize a new instance of the framer.
@@ -33,7 +35,7 @@ def __init__(
3335
"""
3436
self.decoder = decoder
3537
self.client = client
36-
self._header: Dict[str, Any] = {
38+
self._header: dict[str, Any] = {
3739
"lrc": "0000",
3840
"len": 0,
3941
"uid": 0x00,

pymodbus/payload.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
A collection of utilities for building and decoding
44
modbus messages payloads.
55
"""
6+
from __future__ import annotations
7+
68

79
__all__ = [
810
"BinaryPayloadBuilder",
@@ -11,7 +13,6 @@
1113

1214
# pylint: disable=missing-type-doc
1315
from struct import pack, unpack
14-
from typing import List
1516

1617
from pymodbus.constants import Endian
1718
from pymodbus.exceptions import ParameterException
@@ -111,7 +112,7 @@ def to_registers(self):
111112
Log.debug("{}", payload)
112113
return payload
113114

114-
def to_coils(self) -> List[bool]:
115+
def to_coils(self) -> list[bool]:
115116
"""Convert the payload buffer into a coil layout that can be used as a context block.
116117
117118
:returns: The coil layout to use as a block
@@ -120,7 +121,7 @@ def to_coils(self) -> List[bool]:
120121
coils = [bool(int(bit)) for reg in payload for bit in format(reg, "016b")]
121122
return coils
122123

123-
def build(self) -> List[bytes]:
124+
def build(self) -> list[bytes]:
124125
"""Return the payload buffer as a list.
125126
126127
This list is two bytes per element and can
@@ -133,7 +134,7 @@ def build(self) -> List[bytes]:
133134
buffer += b"\x00" * (length % 2)
134135
return [buffer[i : i + 2] for i in range(0, length, 2)]
135136

136-
def add_bits(self, values: List[bool]) -> None:
137+
def add_bits(self, values: list[bool]) -> None:
137138
"""Add a collection of bits to be encoded.
138139
139140
If these are less than a multiple of eight,

pymodbus/repl/client/helper.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ class Result:
232232
"""Represent result command."""
233233

234234
function_code: int | None = None
235-
data: dict[int, Any] | Any = None
235+
data: dict[int, Any] | None = None
236236

237237
def __init__(self, result):
238238
"""Initialize.

pymodbus/repl/server/main.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
"""Repl server main."""
2+
from __future__ import annotations
3+
24
import asyncio
35
import contextlib
46
import json
57
import logging
68
import sys
79
from enum import Enum
810
from pathlib import Path
9-
from typing import List
1011

1112
import typer
1213

@@ -49,7 +50,7 @@ class ModbusFramerTypes(str, Enum):
4950
binary = "binary" # pylint: disable=invalid-name
5051

5152

52-
def _completer(incomplete: str, valid_values: List[str]) -> List[str]:
53+
def _completer(incomplete: str, valid_values: list[str]) -> list[str]:
5354
"""Complete value."""
5455
completion = []
5556
for name in valid_values:
@@ -58,19 +59,19 @@ def _completer(incomplete: str, valid_values: List[str]) -> List[str]:
5859
return completion
5960

6061

61-
def framers(incomplete: str) -> List[str]:
62+
def framers(incomplete: str) -> list[str]:
6263
"""Return an autocompleted list of supported clouds."""
6364
_framers = ["socket", "rtu", "tls", "ascii", "binary"]
6465
return _completer(incomplete, _framers)
6566

6667

67-
def servers(incomplete: str) -> List[str]:
68+
def servers(incomplete: str) -> list[str]:
6869
"""Return an autocompleted list of supported clouds."""
6970
_servers = ["tcp", "serial", "tls", "udp"]
7071
return _completer(incomplete, _servers)
7172

7273

73-
def process_extra_args(extra_args: List[str], modbus_config: dict) -> dict:
74+
def process_extra_args(extra_args: list[str], modbus_config: dict) -> dict:
7475
"""Process extra args passed to server."""
7576
options_stripped = [x.strip().replace("--", "") for x in extra_args[::2]]
7677
extra_args_dict = dict(list(zip(options_stripped, extra_args[1::2])))
@@ -138,7 +139,7 @@ def run(
138139
help="Modbus framer to use",
139140
),
140141
modbus_port: str = typer.Option("5020", "--modbus-port", "-p", help="Modbus port"),
141-
modbus_slave_id: List[int] = typer.Option(
142+
modbus_slave_id: list[int] = typer.Option(
142143
[1], "--slave-id", "-u", help="Supported Modbus slave id's"
143144
),
144145
modbus_config_path: Path = typer.Option(

pymodbus/utilities.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
A collection of utilities for packing data, unpacking
44
data computing checksums, and decode checksums.
55
"""
6+
from __future__ import annotations
7+
68

79
__all__ = [
810
"pack_bitstring",
@@ -17,7 +19,6 @@
1719

1820
# pylint: disable=missing-type-doc
1921
import struct
20-
from typing import List
2122

2223

2324
class ModbusTransactionState: # pylint: disable=too-few-public-methods
@@ -101,7 +102,7 @@ def dict_property(store, index):
101102
# --------------------------------------------------------------------------- #
102103
# Bit packing functions
103104
# --------------------------------------------------------------------------- #
104-
def pack_bitstring(bits: List[bool]) -> bytes:
105+
def pack_bitstring(bits: list[bool]) -> bytes:
105106
"""Create a bytestring out of a list of bits.
106107
107108
:param bits: A list of bits
@@ -128,7 +129,7 @@ def pack_bitstring(bits: List[bool]) -> bytes:
128129
return ret
129130

130131

131-
def unpack_bitstring(data: bytes) -> List[bool]:
132+
def unpack_bitstring(data: bytes) -> list[bool]:
132133
"""Create bit list out of a bytestring.
133134
134135
:param data: The modbus data packet to decode

0 commit comments

Comments
 (0)