Skip to content

Commit 6a4c129

Browse files
committed
Autofix ruff issues, ignore those requiring refactoring
1 parent b7ddf3f commit 6a4c129

File tree

19 files changed

+214
-219
lines changed

19 files changed

+214
-219
lines changed

canopen/emcy.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ class EmcyConsumer:
1616

1717
def __init__(self):
1818
#: Log of all received EMCYs for this node
19-
self.log: List["EmcyError"] = []
19+
self.log: List[EmcyError] = []
2020
#: Only active EMCYs. Will be cleared on Error Reset
21-
self.active: List["EmcyError"] = []
21+
self.active: List[EmcyError] = []
2222
self.callbacks = []
2323
self.emcy_received = threading.Condition()
2424

canopen/lss.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -140,10 +140,7 @@ def send_switch_state_selective(
140140
)
141141

142142
cs = struct.unpack_from("<B", response)[0]
143-
if cs == CS_SWITCH_STATE_SELECTIVE_RESPONSE:
144-
return True
145-
146-
return False
143+
return cs == CS_SWITCH_STATE_SELECTIVE_RESPONSE
147144

148145
def inquire_node_id(self):
149146
"""Read the node id.
@@ -312,10 +309,7 @@ def __send_fast_scan_message(self, id_number, bit_checker, lss_sub, lss_next):
312309
return False
313310

314311
cs = struct.unpack_from("<B", recv_msg)[0]
315-
if cs == CS_IDENTIFY_SLAVE:
316-
return True
317-
318-
return False
312+
return cs == CS_IDENTIFY_SLAVE
319313

320314
def __send_lss_address(self, req_cs, number):
321315
message = bytearray(8)
@@ -408,8 +402,8 @@ def __send_command(self, message):
408402
# TODO check if the response is LSS response message
409403
try:
410404
response = self.responses.get(block=True, timeout=self.RESPONSE_TIMEOUT)
411-
except queue.Empty:
412-
raise LssError("No LSS response received")
405+
except queue.Empty as err:
406+
raise LssError("No LSS response received") from err
413407

414408
return response
415409

canopen/network.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import logging
44
import threading
55
from collections.abc import MutableMapping
6-
from typing import Callable, Dict, Final, Iterator, List, Optional, Union
6+
from typing import Callable, Final, Iterator
77

88
import can
99
from can import Listener
@@ -27,7 +27,7 @@ class Network(MutableMapping):
2727
NOTIFIER_CYCLE: float = 1.0 #: Maximum waiting time for one notifier iteration.
2828
NOTIFIER_SHUTDOWN_TIMEOUT: float = 5.0 #: Maximum waiting time to stop notifiers.
2929

30-
def __init__(self, bus: Optional[can.BusABC] = None):
30+
def __init__(self, bus: can.BusABC | None = None):
3131
"""
3232
:param can.BusABC bus:
3333
A python-can bus instance to re-use.
@@ -40,9 +40,9 @@ def __init__(self, bus: Optional[can.BusABC] = None):
4040
#: List of :class:`can.Listener` objects.
4141
#: Includes at least MessageListener.
4242
self.listeners = [MessageListener(self)]
43-
self.notifier: Optional[can.Notifier] = None
44-
self.nodes: Dict[int, Union[RemoteNode, LocalNode]] = {}
45-
self.subscribers: Dict[int, List[Callback]] = {}
43+
self.notifier: can.Notifier | None = None
44+
self.nodes: dict[int, RemoteNode | LocalNode] = {}
45+
self.subscribers: dict[int, list[Callback]] = {}
4646
self.send_lock = threading.Lock()
4747
self.sync = SyncProducer(self)
4848
self.time = TimeProducer(self)
@@ -61,7 +61,7 @@ def subscribe(self, can_id: int, callback: Callback) -> None:
6161
:param callback:
6262
Function to call when message is received.
6363
"""
64-
self.subscribers.setdefault(can_id, list())
64+
self.subscribers.setdefault(can_id, [])
6565
if callback not in self.subscribers[can_id]:
6666
self.subscribers[can_id].append(callback)
6767

@@ -133,8 +133,8 @@ def __exit__(self, type, value, traceback):
133133

134134
def add_node(
135135
self,
136-
node: Union[int, RemoteNode, LocalNode],
137-
object_dictionary: Union[str, ObjectDictionary, None] = None,
136+
node: int | RemoteNode | LocalNode,
137+
object_dictionary: str | ObjectDictionary | None = None,
138138
upload_eds: bool = False,
139139
) -> RemoteNode:
140140
"""Add a remote node to the network.
@@ -163,7 +163,7 @@ def add_node(
163163
def create_node(
164164
self,
165165
node: int,
166-
object_dictionary: Union[str, ObjectDictionary, None] = None,
166+
object_dictionary: str | ObjectDictionary | None = None,
167167
) -> LocalNode:
168168
"""Create a local node in the network.
169169
@@ -261,10 +261,10 @@ def check(self) -> None:
261261
logger.error("An error has caused receiving of messages to stop")
262262
raise exc
263263

264-
def __getitem__(self, node_id: int) -> Union[RemoteNode, LocalNode]:
264+
def __getitem__(self, node_id: int) -> RemoteNode | LocalNode:
265265
return self.nodes[node_id]
266266

267-
def __setitem__(self, node_id: int, node: Union[RemoteNode, LocalNode]):
267+
def __setitem__(self, node_id: int, node: RemoteNode | LocalNode):
268268
assert node_id == node.id
269269
if node_id in self.nodes:
270270
# Remove old callbacks
@@ -286,7 +286,7 @@ def __len__(self) -> int:
286286
class _UninitializedNetwork(Network):
287287
"""Empty network implementation as a placeholder before actual initialization."""
288288

289-
def __init__(self, bus: Optional[can.BusABC] = None):
289+
def __init__(self, bus: can.BusABC | None = None):
290290
"""Do not initialize attributes, by skipping the parent constructor."""
291291

292292
def __getattribute__(self, name):
@@ -397,10 +397,10 @@ class NodeScanner:
397397

398398
SERVICES = (0x700, 0x580, 0x180, 0x280, 0x380, 0x480, 0x80)
399399

400-
def __init__(self, network: Optional[Network] = None):
400+
def __init__(self, network: Network | None = None):
401401
self.network = network
402402
#: A :class:`list` of nodes discovered
403-
self.nodes: List[int] = []
403+
self.nodes: list[int] = []
404404

405405
def on_message_received(self, can_id: int):
406406
service = can_id & 0x780

canopen/nmt.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,7 @@ def state(self, new_state: str):
102102
code = NMT_COMMANDS[new_state]
103103
else:
104104
raise ValueError(
105-
"'%s' is an invalid state. Must be one of %s."
106-
% (new_state, ", ".join(NMT_COMMANDS))
105+
f"'{new_state}' is an invalid state. Must be one of {', '.join(NMT_COMMANDS)}."
107106
)
108107

109108
self.send_command(code)
@@ -112,7 +111,7 @@ def state(self, new_state: str):
112111
class NmtMaster(NmtBase):
113112

114113
def __init__(self, node_id: int):
115-
super(NmtMaster, self).__init__(node_id)
114+
super().__init__(node_id)
116115
self._state_received = None
117116
self._node_guarding_producer: Optional[PeriodicMessageTask] = None
118117
#: Timestamp of last heartbeat message
@@ -143,7 +142,7 @@ def send_command(self, code: int):
143142
:param code:
144143
NMT command code.
145144
"""
146-
super(NmtMaster, self).send_command(code)
145+
super().send_command(code)
147146
logger.info("Sending NMT command 0x%X to node %d", code, self.id)
148147
self.network.send_message(0, [code, self.id])
149148

@@ -205,13 +204,13 @@ class NmtSlave(NmtBase):
205204
"""
206205

207206
def __init__(self, node_id: int, local_node):
208-
super(NmtSlave, self).__init__(node_id)
207+
super().__init__(node_id)
209208
self._send_task: Optional[PeriodicMessageTask] = None
210209
self._heartbeat_time_ms = 0
211210
self._local_node = local_node
212211

213212
def on_command(self, can_id, data, timestamp):
214-
super(NmtSlave, self).on_command(can_id, data, timestamp)
213+
super().on_command(can_id, data, timestamp)
215214
self.update_heartbeat()
216215

217216
def send_command(self, code: int) -> None:
@@ -221,7 +220,7 @@ def send_command(self, code: int) -> None:
221220
NMT command code.
222221
"""
223222
old_state = self._state
224-
super(NmtSlave, self).send_command(code)
223+
super().send_command(code)
225224

226225
if self._state == 0:
227226
logger.info("Sending boot-up message")

canopen/node/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
from canopen.node.local import LocalNode
22
from canopen.node.remote import RemoteNode
3+
4+
__all__ = ["LocalNode", "RemoteNode"]

canopen/node/local.py

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

33
import logging
4-
from typing import Dict, Union
54

65
import canopen.network
76
from canopen import objectdictionary
@@ -20,11 +19,11 @@ class LocalNode(BaseNode):
2019
def __init__(
2120
self,
2221
node_id: int,
23-
object_dictionary: Union[ObjectDictionary, str],
22+
object_dictionary: ObjectDictionary | str,
2423
):
25-
super(LocalNode, self).__init__(node_id, object_dictionary)
24+
super().__init__(node_id, object_dictionary)
2625

27-
self.data_store: Dict[int, Dict[int, bytes]] = {}
26+
self.data_store: dict[int, dict[int, bytes]] = {}
2827
self._read_callbacks = []
2928
self._write_callbacks = []
3029

canopen/node/remote.py

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

33
import logging
4-
from typing import TextIO, Union
4+
from typing import TextIO
55

66
import canopen.network
77
from canopen.emcy import EmcyConsumer
@@ -30,10 +30,10 @@ class RemoteNode(BaseNode):
3030
def __init__(
3131
self,
3232
node_id: int,
33-
object_dictionary: Union[ObjectDictionary, str, TextIO],
33+
object_dictionary: ObjectDictionary | str | TextIO,
3434
load_od: bool = False,
3535
):
36-
super(RemoteNode, self).__init__(node_id, object_dictionary)
36+
super().__init__(node_id, object_dictionary)
3737

3838
#: Enable WORKAROUND for reversed PDO mapping entries
3939
self.curtis_hack = False
@@ -164,7 +164,7 @@ def load_configuration(self) -> None:
164164
if 0x1400 <= obj.index < 0x1C00:
165165
# Ignore PDO related objects
166166
continue
167-
if isinstance(obj, ODRecord) or isinstance(obj, ODArray):
167+
if isinstance(obj, (ODRecord, ODArray)):
168168
for subobj in obj.values():
169169
if (
170170
isinstance(subobj, ODVariable)

0 commit comments

Comments
 (0)