Skip to content

Commit 0178355

Browse files
authored
Extend ruff linter configuration (#1724)
* update ruff configuration * skip test_send_periodic_duration on PyPy * remove format-code.yml
1 parent bcd2ee5 commit 0178355

35 files changed

+188
-198
lines changed

.github/workflows/format-code.yml

Lines changed: 0 additions & 29 deletions
This file was deleted.

can/bus.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ def wrapped_stop_method(remove_task: bool = True) -> None:
281281
pass # allow the task to be already removed
282282
original_stop_method()
283283

284-
task.stop = wrapped_stop_method # type: ignore
284+
task.stop = wrapped_stop_method # type: ignore[method-assign]
285285

286286
if store_task:
287287
self._periodic_tasks.append(task)
@@ -401,7 +401,8 @@ def set_filters(
401401
messages based only on the arbitration ID and mask.
402402
"""
403403
self._filters = filters or None
404-
self._apply_filters(self._filters)
404+
with contextlib.suppress(NotImplementedError):
405+
self._apply_filters(self._filters)
405406

406407
def _apply_filters(self, filters: Optional[can.typechecking.CanFilters]) -> None:
407408
"""
@@ -411,6 +412,7 @@ def _apply_filters(self, filters: Optional[can.typechecking.CanFilters]) -> None
411412
:param filters:
412413
See :meth:`~can.BusABC.set_filters` for details.
413414
"""
415+
raise NotImplementedError
414416

415417
def _matches_filters(self, msg: Message) -> bool:
416418
"""Checks whether the given message matches at least one of the
@@ -450,6 +452,7 @@ def _matches_filters(self, msg: Message) -> bool:
450452

451453
def flush_tx_buffer(self) -> None:
452454
"""Discard every message that may be queued in the output buffer(s)."""
455+
raise NotImplementedError
453456

454457
def shutdown(self) -> None:
455458
"""

can/ctypesutil.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# type: ignore
21
"""
32
This module contains common `ctypes` utils.
43
"""
@@ -11,11 +10,10 @@
1110

1211
__all__ = ["CLibrary", "HANDLE", "PHANDLE", "HRESULT"]
1312

14-
15-
try:
13+
if sys.platform == "win32":
1614
_LibBase = ctypes.WinDLL
1715
_FUNCTION_TYPE = ctypes.WINFUNCTYPE
18-
except AttributeError:
16+
else:
1917
_LibBase = ctypes.CDLL
2018
_FUNCTION_TYPE = ctypes.CFUNCTYPE
2119

@@ -60,7 +58,7 @@ def map_symbol(
6058
f'Could not map function "{func_name}" from library {self._name}'
6159
) from None
6260

63-
func._name = func_name # pylint: disable=protected-access
61+
func._name = func_name # type: ignore[attr-defined] # pylint: disable=protected-access
6462
log.debug(
6563
'Wrapped function "%s", result type: %s, error_check %s',
6664
func_name,

can/interface.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ def _get_class_for_interface(interface: str) -> Type[BusABC]:
6161
bustype="interface",
6262
context="config_context",
6363
)
64-
def Bus(
64+
def Bus( # noqa: N802
6565
channel: Optional[Channel] = None,
6666
interface: Optional[str] = None,
6767
config_context: Optional[str] = None,

can/interfaces/etas/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -229,10 +229,10 @@ def _apply_filters(self, filters: Optional[can.typechecking.CanFilters]) -> None
229229

230230
self._oci_filters = (ctypes.POINTER(OCI_CANRxFilterEx) * len(filters))()
231231

232-
for i, filter in enumerate(filters):
232+
for i, filter_ in enumerate(filters):
233233
f = OCI_CANRxFilterEx()
234-
f.frameIDValue = filter["can_id"]
235-
f.frameIDMask = filter["can_mask"]
234+
f.frameIDValue = filter_["can_id"]
235+
f.frameIDMask = filter_["can_mask"]
236236
f.tag = 0
237237
f.flagsValue = 0
238238
if self.receive_own_messages:
@@ -241,7 +241,7 @@ def _apply_filters(self, filters: Optional[can.typechecking.CanFilters]) -> None
241241
else:
242242
# enable the SR bit in the mask. since the bit is 0 in flagsValue -> do not self-receive
243243
f.flagsMask = OCI_CAN_MSG_FLAG_SELFRECEPTION
244-
if filter.get("extended"):
244+
if filter_.get("extended"):
245245
f.flagsValue |= OCI_CAN_MSG_FLAG_EXTENDED
246246
f.flagsMask |= OCI_CAN_MSG_FLAG_EXTENDED
247247
self._oci_filters[i].contents = f

can/interfaces/gs_usb.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,8 @@ def send(self, msg: can.Message, timeout: Optional[float] = None):
9595

9696
try:
9797
self.gs_usb.send(frame)
98-
except usb.core.USBError:
99-
raise CanOperationError("The message could not be sent")
98+
except usb.core.USBError as exc:
99+
raise CanOperationError("The message could not be sent") from exc
100100

101101
def _recv_internal(
102102
self, timeout: Optional[float]

can/interfaces/ics_neovi/neovi_bus.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,10 @@ def __reduce__(self):
109109
def error_number(self) -> int:
110110
"""Deprecated. Renamed to :attr:`can.CanError.error_code`."""
111111
warn(
112-
"ICSApiError::error_number has been renamed to error_code defined by CanError",
112+
"ICSApiError::error_number has been replaced by ICSApiError.error_code in python-can 4.0"
113+
"and will be remove in version 5.0.",
113114
DeprecationWarning,
115+
stacklevel=2,
114116
)
115117
return self.error_code
116118

@@ -223,10 +225,8 @@ def __init__(self, channel, can_filters=None, **kwargs):
223225
self._use_system_timestamp = bool(kwargs.get("use_system_timestamp", False))
224226
self._receive_own_messages = kwargs.get("receive_own_messages", True)
225227

226-
self.channel_info = "{} {} CH:{}".format(
227-
self.dev.Name,
228-
self.get_serial_number(self.dev),
229-
self.channels,
228+
self.channel_info = (
229+
f"{self.dev.Name} {self.get_serial_number(self.dev)} CH:{self.channels}"
230230
)
231231
logger.info(f"Using device: {self.channel_info}")
232232

can/interfaces/ixxat/canlib_vcinpl.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,8 @@ def __vciFormatErrorExtended(
7979
Formatted string
8080
"""
8181
# TODO: make sure we don't generate another exception
82-
return "{} - arguments were {}".format(
83-
__vciFormatError(library_instance, function, vret), args
82+
return (
83+
f"{__vciFormatError(library_instance, function, vret)} - arguments were {args}"
8484
)
8585

8686

@@ -512,13 +512,11 @@ def __init__(
512512
if unique_hardware_id is None:
513513
raise VCIDeviceNotFoundError(
514514
"No IXXAT device(s) connected or device(s) in use by other process(es)."
515-
)
515+
) from None
516516
else:
517517
raise VCIDeviceNotFoundError(
518-
"Unique HW ID {} not connected or not available.".format(
519-
unique_hardware_id
520-
)
521-
)
518+
f"Unique HW ID {unique_hardware_id} not connected or not available."
519+
) from None
522520
else:
523521
if (unique_hardware_id is None) or (
524522
self._device_info.UniqueHardwareId.AsChar
@@ -815,7 +813,8 @@ def _send_periodic_internal(
815813
# fallback to thread based cyclic task
816814
warnings.warn(
817815
f"{self.__class__.__name__} falls back to a thread-based cyclic task, "
818-
"when the `modifier_callback` argument is given."
816+
"when the `modifier_callback` argument is given.",
817+
stacklevel=3,
819818
)
820819
return BusABC._send_periodic_internal(
821820
self,

can/interfaces/ixxat/canlib_vcinpl2.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,8 @@ def __vciFormatErrorExtended(
7777
Formatted string
7878
"""
7979
# TODO: make sure we don't generate another exception
80-
return "{} - arguments were {}".format(
81-
__vciFormatError(library_instance, function, vret), args
80+
return (
81+
f"{__vciFormatError(library_instance, function, vret)} - arguments were {args}"
8282
)
8383

8484

@@ -553,13 +553,11 @@ def __init__(
553553
if unique_hardware_id is None:
554554
raise VCIDeviceNotFoundError(
555555
"No IXXAT device(s) connected or device(s) in use by other process(es)."
556-
)
556+
) from None
557557
else:
558558
raise VCIDeviceNotFoundError(
559-
"Unique HW ID {} not connected or not available.".format(
560-
unique_hardware_id
561-
)
562-
)
559+
f"Unique HW ID {unique_hardware_id} not connected or not available."
560+
) from None
563561
else:
564562
if (unique_hardware_id is None) or (
565563
self._device_info.UniqueHardwareId.AsChar
@@ -579,7 +577,9 @@ def __init__(
579577
ctypes.byref(self._device_handle),
580578
)
581579
except Exception as exception:
582-
raise CanInitializationError(f"Could not open device: {exception}")
580+
raise CanInitializationError(
581+
f"Could not open device: {exception}"
582+
) from exception
583583

584584
log.info("Using unique HW ID %s", self._device_info.UniqueHardwareId.AsChar)
585585

@@ -600,7 +600,7 @@ def __init__(
600600
except Exception as exception:
601601
raise CanInitializationError(
602602
f"Could not open and initialize channel: {exception}"
603-
)
603+
) from exception
604604

605605
# Signal TX/RX events when at least one frame has been handled
606606
_canlib.canChannelInitialize(
@@ -959,7 +959,8 @@ def _send_periodic_internal(
959959
# fallback to thread based cyclic task
960960
warnings.warn(
961961
f"{self.__class__.__name__} falls back to a thread-based cyclic task, "
962-
"when the `modifier_callback` argument is given."
962+
"when the `modifier_callback` argument is given.",
963+
stacklevel=3,
963964
)
964965
return BusABC._send_periodic_internal(
965966
self,

can/interfaces/kvaser/canlib.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,7 @@ def __init__(
458458
try:
459459
channel = int(channel)
460460
except ValueError:
461-
raise ValueError("channel must be an integer")
461+
raise ValueError("channel must be an integer") from None
462462

463463
self.channel = channel
464464
self.single_handle = single_handle

can/interfaces/nixnet.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,10 +192,12 @@ def __init__(
192192

193193
@property
194194
def fd(self) -> bool:
195+
class_name = self.__class__.__name__
195196
warnings.warn(
196-
"The NiXNETcanBus.fd property is deprecated and superseded by "
197-
"BusABC.protocol. It is scheduled for removal in version 5.0.",
197+
f"The {class_name}.fd property is deprecated and superseded by "
198+
f"{class_name}.protocol. It is scheduled for removal in python-can version 5.0.",
198199
DeprecationWarning,
200+
stacklevel=2,
199201
)
200202
return self._can_protocol is CanProtocol.CAN_FD
201203

can/interfaces/pcan/basic.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -694,9 +694,9 @@ def Initialize(
694694
self,
695695
Channel,
696696
Btr0Btr1,
697-
HwType=TPCANType(0),
698-
IOPort=c_uint(0),
699-
Interrupt=c_ushort(0),
697+
HwType=TPCANType(0), # noqa: B008
698+
IOPort=c_uint(0), # noqa: B008
699+
Interrupt=c_ushort(0), # noqa: B008
700700
):
701701
"""Initializes a PCAN Channel
702702

can/interfaces/pcan/pcan.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -657,10 +657,12 @@ def shutdown(self):
657657

658658
@property
659659
def fd(self) -> bool:
660+
class_name = self.__class__.__name__
660661
warnings.warn(
661-
"The PcanBus.fd property is deprecated and superseded by BusABC.protocol. "
662-
"It is scheduled for removal in version 5.0.",
662+
f"The {class_name}.fd property is deprecated and superseded by {class_name}.protocol. "
663+
"It is scheduled for removal in python-can version 5.0.",
663664
DeprecationWarning,
665+
stacklevel=2,
664666
)
665667
return self._can_protocol is CanProtocol.CAN_FD
666668

can/interfaces/robotell.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,7 @@ def fileno(self):
376376
except io.UnsupportedOperation:
377377
raise NotImplementedError(
378378
"fileno is not implemented using current CAN bus on this platform"
379-
)
379+
) from None
380380
except Exception as exception:
381381
raise CanOperationError("Cannot fetch fileno") from exception
382382

can/interfaces/seeedstudio/seeedstudio.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,6 @@ def __init__(
6363
frame_type="STD",
6464
operation_mode="normal",
6565
bitrate=500000,
66-
*args,
6766
**kwargs,
6867
):
6968
"""
@@ -115,7 +114,7 @@ def __init__(
115114
"could not create the serial device"
116115
) from error
117116

118-
super().__init__(channel=channel, *args, **kwargs)
117+
super().__init__(channel=channel, **kwargs)
119118
self.init_frame()
120119

121120
def shutdown(self):

can/interfaces/serial/serial_can.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,13 +131,15 @@ def send(self, msg: Message, timeout: Optional[float] = None) -> None:
131131
try:
132132
timestamp = struct.pack("<I", int(msg.timestamp * 1000))
133133
except struct.error:
134-
raise ValueError("Timestamp is out of range")
134+
raise ValueError(f"Timestamp is out of range: {msg.timestamp}") from None
135135

136136
# Pack arbitration ID
137137
try:
138138
arbitration_id = struct.pack("<I", msg.arbitration_id)
139139
except struct.error:
140-
raise ValueError("Arbitration ID is out of range")
140+
raise ValueError(
141+
f"Arbitration ID is out of range: {msg.arbitration_id}"
142+
) from None
141143

142144
# Assemble message
143145
byte_msg = bytearray()
@@ -222,7 +224,7 @@ def fileno(self) -> int:
222224
except io.UnsupportedOperation:
223225
raise NotImplementedError(
224226
"fileno is not implemented using current CAN bus on this platform"
225-
)
227+
) from None
226228
except Exception as exception:
227229
raise CanOperationError("Cannot fetch fileno") from exception
228230

can/interfaces/slcan.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ def fileno(self) -> int:
268268
except io.UnsupportedOperation:
269269
raise NotImplementedError(
270270
"fileno is not implemented using current CAN bus on this platform"
271-
)
271+
) from None
272272
except Exception as exception:
273273
raise CanOperationError("Cannot fetch fileno") from exception
274274

0 commit comments

Comments
 (0)