Skip to content

Commit 270224c

Browse files
authored
Fix formatter and bump ci tools (#1167)
* Bump CI tool versions * Fix many linter issues * Format code with black
1 parent 38889ec commit 270224c

30 files changed

+117
-126
lines changed

can/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
log = logging.getLogger("can")
1414

15-
rc: Dict[str, Any] = dict()
15+
rc: Dict[str, Any] = {}
1616

1717
from .listener import Listener, BufferedReader, RedirectReader, AsyncBufferedReader
1818

can/interfaces/canalystii.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def __init__(
5353
elif isinstance(channel, int):
5454
self.channels = [channel]
5555
else: # Sequence[int]
56-
self.channels = [c for c in channel]
56+
self.channels = list(channel)
5757

5858
self.rx_queue = collections.deque(
5959
maxlen=rx_queue_size

can/interfaces/cantact.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def _detect_available_configs():
3939

4040
channels = []
4141
for i in range(0, interface.channel_count()):
42-
channels.append({"interface": "cantact", "channel": "ch:%d" % i})
42+
channels.append({"interface": "cantact", "channel": f"ch:{i}"})
4343
return channels
4444

4545
def __init__(

can/interfaces/ics_neovi/neovi_bus.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -226,8 +226,8 @@ def channel_to_netid(channel_name_or_id):
226226
channel = getattr(ics, netid)
227227
else:
228228
raise ValueError(
229-
"channel must be an integer or " "a valid ICS channel name"
230-
)
229+
"channel must be an integer or a valid ICS channel name"
230+
) from None
231231
return channel
232232

233233
@staticmethod

can/interfaces/ixxat/canlib.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -604,12 +604,12 @@ def _inWaiting(self):
604604
return 1
605605

606606
def flush_tx_buffer(self):
607-
""" Flushes the transmit buffer on the IXXAT """
607+
"""Flushes the transmit buffer on the IXXAT"""
608608
# TODO #64: no timeout?
609609
_canlib.canChannelWaitTxEvent(self._channel_handle, constants.INFINITE)
610610

611611
def _recv_internal(self, timeout):
612-
""" Read a message from IXXAT device. """
612+
"""Read a message from IXXAT device."""
613613

614614
# TODO: handling CAN error messages?
615615
data_received = False

can/interfaces/ixxat/exceptions.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,15 @@
2121

2222

2323
class VCITimeout(CanTimeoutError):
24-
""" Wraps the VCI_E_TIMEOUT error """
24+
"""Wraps the VCI_E_TIMEOUT error"""
2525

2626

2727
class VCIError(CanOperationError):
28-
""" Try to display errors that occur within the wrapped C library nicely. """
28+
"""Try to display errors that occur within the wrapped C library nicely."""
2929

3030

3131
class VCIRxQueueEmptyError(VCIError):
32-
""" Wraps the VCI_E_RXQUEUE_EMPTY error """
32+
"""Wraps the VCI_E_RXQUEUE_EMPTY error"""
3333

3434
def __init__(self):
3535
super().__init__("Receive queue is empty")

can/interfaces/kvaser/canlib.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -713,11 +713,7 @@ def get_channel_info(channel):
713713
ctypes.sizeof(number),
714714
)
715715

716-
return "%s, S/N %d (#%d)" % (
717-
name.value.decode("ascii"),
718-
serial.value,
719-
number.value + 1,
720-
)
716+
return f"{name.value.decode('ascii')}, S/N {serial.value} (#{number.value + 1})"
721717

722718

723719
init_kvaser_library()

can/interfaces/neousys/neousys.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747

4848

4949
class NeousysCanSetup(Structure):
50-
""" C CAN Setup struct """
50+
"""C CAN Setup struct"""
5151

5252
_fields_ = [
5353
("bitRate", c_uint),
@@ -58,7 +58,7 @@ class NeousysCanSetup(Structure):
5858

5959

6060
class NeousysCanMsg(Structure):
61-
""" C CAN Message struct """
61+
"""C CAN Message struct"""
6262

6363
_fields_ = [
6464
("id", c_uint),
@@ -75,7 +75,7 @@ class NeousysCanMsg(Structure):
7575
# valid:1~4, Resynchronization Jump Width in time quanta
7676
# valid:1~1023, CAN_CLK divider used to determine time quanta
7777
class NeousysCanBitClk(Structure):
78-
""" C CAN BIT Clock struct """
78+
"""C CAN BIT Clock struct"""
7979

8080
_fields_ = [
8181
("syncPropPhase1Seg", c_ushort),

can/interfaces/nixnet.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
)
3131
except ImportError:
3232
logger.error("Error, NIXNET python module cannot be loaded.")
33-
raise ImportError()
33+
raise
3434
else:
3535
logger.error("NI-XNET interface is only available on Windows systems")
3636
raise NotImplementedError("NiXNET is not supported on not Win32 platforms")

can/interfaces/seeedstudio/seeedstudio.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ def __init__(
113113
"could not create the serial device"
114114
) from error
115115

116-
super(SeeedBus, self).__init__(channel=channel, *args, **kwargs)
116+
super().__init__(channel=channel, *args, **kwargs)
117117
self.init_frame()
118118

119119
def shutdown(self):

can/interfaces/socketcan/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from typing import cast, Iterable, Optional
1212

1313
from can.interfaces.socketcan.constants import CAN_EFF_FLAG
14-
import can.typechecking as typechecking
14+
from can import typechecking
1515

1616
log = logging.getLogger(__name__)
1717

can/interfaces/systec/structures.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ class HardwareInfoEx(Structure):
268268
]
269269

270270
def __init__(self):
271-
super(HardwareInfoEx, self).__init__(sizeof(HardwareInfoEx))
271+
super().__init__(sizeof(HardwareInfoEx))
272272

273273
def __eq__(self, other):
274274
if not isinstance(other, HardwareInfoEx):

can/interfaces/udp_multicast/bus.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -121,13 +121,13 @@ def _recv_internal(self, timeout: Optional[float]):
121121

122122
return can_message, False
123123

124-
def send(self, message: can.Message, timeout: Optional[float] = None) -> None:
125-
if not self.is_fd and message.is_fd:
124+
def send(self, msg: can.Message, timeout: Optional[float] = None) -> None:
125+
if not self.is_fd and msg.is_fd:
126126
raise can.CanOperationError(
127127
"cannot send FD message over bus with CAN FD disabled"
128128
)
129129

130-
data = pack_message(message)
130+
data = pack_message(msg)
131131
self._multicast.send(data, timeout)
132132

133133
def fileno(self) -> int:
@@ -186,8 +186,9 @@ def __init__(
186186
sock = self._create_socket(address_family)
187187
except OSError as error:
188188
log.info(
189-
f"could not connect to the multicast IP network of candidate %s; reason: {error}",
189+
"could not connect to the multicast IP network of candidate %s; reason: %s",
190190
connection_candidates,
191+
error,
191192
)
192193
if sock is not None:
193194
self._socket = sock

can/interfaces/vector/canlib.py

+11-12
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,6 @@
3838
)
3939
from can.typechecking import AutoDetectedConfig, CanFilters
4040

41-
from .exceptions import VectorError
42-
4341
# Define Module Logger
4442
# ====================
4543
LOG = logging.getLogger(__name__)
@@ -140,7 +138,8 @@ def __init__(
140138
"""
141139
if os.name != "nt" and not kwargs.get("_testing", False):
142140
raise CanInterfaceNotImplementedError(
143-
f'The Vector interface is only supported on Windows, but you are running "{os.name}"'
141+
f"The Vector interface is only supported on Windows, "
142+
f'but you are running "{os.name}"'
144143
)
145144

146145
if xldriver is None:
@@ -163,7 +162,7 @@ def __init__(
163162
self._app_name = app_name.encode() if app_name is not None else b""
164163
self.channel_info = "Application %s: %s" % (
165164
app_name,
166-
", ".join("CAN %d" % (ch + 1) for ch in self.channels),
165+
", ".join(f"CAN {ch + 1}" for ch in self.channels),
167166
)
168167

169168
if serial is not None:
@@ -358,8 +357,8 @@ def _apply_filters(self, filters) -> None:
358357
if can_filter.get("extended")
359358
else xldefine.XL_AcceptanceFilter.XL_CAN_STD,
360359
)
361-
except VectorOperationError as exc:
362-
LOG.warning("Could not set filters: %s", exc)
360+
except VectorOperationError as exception:
361+
LOG.warning("Could not set filters: %s", exception)
363362
# go to fallback
364363
else:
365364
self._is_filtered = True
@@ -400,8 +399,8 @@ def _recv_internal(
400399
else:
401400
msg = self._recv_can()
402401

403-
except VectorOperationError as exc:
404-
if exc.error_code != xldefine.XL_Status.XL_ERR_QUEUE_IS_EMPTY:
402+
except VectorOperationError as exception:
403+
if exception.error_code != xldefine.XL_Status.XL_ERR_QUEUE_IS_EMPTY:
405404
raise
406405
else:
407406
if msg:
@@ -435,7 +434,7 @@ def _recv_canfd(self) -> Optional[Message]:
435434
data_struct = xl_can_rx_event.tagData.canTxOkMsg
436435
else:
437436
self.handle_canfd_event(xl_can_rx_event)
438-
return
437+
return None
439438

440439
msg_id = data_struct.canId
441440
dlc = dlc2len(data_struct.dlc)
@@ -475,7 +474,7 @@ def _recv_can(self) -> Optional[Message]:
475474

476475
if xl_event.tag != xldefine.XL_EventTags.XL_RECEIVE_MSG:
477476
self.handle_can_event(xl_event)
478-
return
477+
return None
479478

480479
msg_id = xl_event.tagData.msg.id
481480
dlc = xl_event.tagData.msg.dlc
@@ -520,8 +519,8 @@ def handle_canfd_event(self, event: xlclass.XLcanRxEvent) -> None:
520519
when `event.tag` is not `XL_CAN_EV_TAG_RX_OK` or `XL_CAN_EV_TAG_TX_OK`.
521520
Subclasses can implement this method.
522521
523-
:param event: `XLcanRxEvent` that could have a `XL_CAN_EV_TAG_RX_ERROR`, `XL_CAN_EV_TAG_TX_ERROR`,
524-
`XL_TIMER` or `XL_CAN_EV_TAG_CHIP_STATE` tag.
522+
:param event: `XLcanRxEvent` that could have a `XL_CAN_EV_TAG_RX_ERROR`,
523+
`XL_CAN_EV_TAG_TX_ERROR`, `XL_TIMER` or `XL_CAN_EV_TAG_CHIP_STATE` tag.
525524
"""
526525

527526
def send(self, msg: Message, timeout: Optional[float] = None):

can/interfaces/virtual.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def __init__(
6767

6868
# the channel identifier may be an arbitrary object
6969
self.channel_id = channel
70-
self.channel_info = "Virtual bus channel {}".format(self.channel_id)
70+
self.channel_info = f"Virtual bus channel {self.channel_id}"
7171
self.receive_own_messages = receive_own_messages
7272
self._open = True
7373

can/io/asc.py

+16-14
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
- under `test/data/logfile.asc`
77
"""
88

9-
from typing import cast, Any, Generator, IO, List, Optional, Union, Dict
9+
from typing import cast, Any, Generator, IO, List, Optional, Dict
1010

1111
from datetime import datetime
1212
import time
@@ -73,8 +73,10 @@ def _extract_header(self):
7373
elif lower_case.startswith("base"):
7474
try:
7575
_, base, _, timestamp_format = line.split()
76-
except ValueError:
77-
raise Exception("Unsupported header string format: {}".format(line))
76+
except ValueError as exception:
77+
raise Exception(
78+
f"Unsupported header string format: {line}"
79+
) from exception
7880
self.base = base
7981
self._converted_base = self._check_base(self.base)
8082
self.timestamps_format = timestamp_format
@@ -135,8 +137,8 @@ def _process_classic_can_frame(
135137
# Error Frame
136138
msg_kwargs["is_error_frame"] = True
137139
else:
138-
abr_id_str, dir, rest_of_message = line.split(None, 2)
139-
msg_kwargs["is_rx"] = dir == "Rx"
140+
abr_id_str, direction, rest_of_message = line.split(None, 2)
141+
msg_kwargs["is_rx"] = direction == "Rx"
140142
self._extract_can_id(abr_id_str, msg_kwargs)
141143

142144
if rest_of_message[0].lower() == "r":
@@ -164,10 +166,10 @@ def _process_classic_can_frame(
164166
return Message(**msg_kwargs)
165167

166168
def _process_fd_can_frame(self, line: str, msg_kwargs: Dict[str, Any]) -> Message:
167-
channel, dir, rest_of_message = line.split(None, 2)
169+
channel, direction, rest_of_message = line.split(None, 2)
168170
# See ASCWriter
169171
msg_kwargs["channel"] = int(channel) - 1
170-
msg_kwargs["is_rx"] = dir == "Rx"
172+
msg_kwargs["is_rx"] = direction == "Rx"
171173

172174
# CAN FD error frame
173175
if rest_of_message.strip()[:10].lower() == "errorframe":
@@ -291,7 +293,7 @@ def __init__(
291293

292294
# write start of file header
293295
now = datetime.now().strftime(self.FORMAT_START_OF_FILE_DATE)
294-
self.file.write("date %s\n" % now)
296+
self.file.write(f"date {now}\n")
295297
self.file.write("base hex timestamps absolute\n")
296298
self.file.write("internal events logged\n")
297299

@@ -327,7 +329,7 @@ def log_event(self, message: str, timestamp: Optional[float] = None) -> None:
327329
formatted_date = time.strftime(
328330
self.FORMAT_DATE.format(mlsec), time.localtime(self.last_timestamp)
329331
)
330-
self.file.write("Begin Triggerblock %s\n" % formatted_date)
332+
self.file.write(f"Begin Triggerblock {formatted_date}\n")
331333
self.header_written = True
332334
self.log_event("Start of measurement") # caution: this is a recursive call!
333335
# Use last known timestamp if unknown
@@ -342,15 +344,15 @@ def log_event(self, message: str, timestamp: Optional[float] = None) -> None:
342344
def on_message_received(self, msg: Message) -> None:
343345

344346
if msg.is_error_frame:
345-
self.log_event("{} ErrorFrame".format(self.channel), msg.timestamp)
347+
self.log_event(f"{self.channel} ErrorFrame", msg.timestamp)
346348
return
347349
if msg.is_remote_frame:
348-
dtype = "r {:x}".format(msg.dlc) # New after v8.5
350+
dtype = f"r {msg.dlc:x}" # New after v8.5
349351
data: List[str] = []
350352
else:
351-
dtype = "d {:x}".format(msg.dlc)
352-
data = ["{:02X}".format(byte) for byte in msg.data]
353-
arb_id = "{:X}".format(msg.arbitration_id)
353+
dtype = f"d {msg.dlc:x}"
354+
data = [f"{byte:02X}" for byte in msg.data]
355+
arb_id = f"{msg.arbitration_id:X}"
354356
if msg.is_extended_id:
355357
arb_id += "x"
356358
channel = channel2int(msg.channel)

can/io/blf.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ def _parse_data(self, data):
228228
if pos + 8 > max_pos:
229229
# Not enough data in container
230230
return
231-
raise BLFParseError("Could not find next object")
231+
raise BLFParseError("Could not find next object") from None
232232
header = unpack_obj_header_base(data, pos)
233233
# print(header)
234234
signature, _, header_version, obj_size, obj_type = header
@@ -258,7 +258,7 @@ def _parse_data(self, data):
258258
factor = 1e-5 if flags == 1 else 1e-9
259259
timestamp = timestamp * factor + start_timestamp
260260

261-
if obj_type == CAN_MESSAGE or obj_type == CAN_MESSAGE2:
261+
if obj_type in (CAN_MESSAGE, CAN_MESSAGE2):
262262
channel, flags, dlc, can_id, can_data = unpack_can_msg(data, pos)
263263
yield Message(
264264
timestamp=timestamp,

can/io/generic.py

+1
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ def __init__(
4343
# file is None or some file-like object
4444
self.file = cast(Optional[can.typechecking.FileLike], file)
4545
else:
46+
# pylint: disable=consider-using-with
4647
# file is some path-like object
4748
self.file = open(cast(can.typechecking.StringPathLike, file), mode)
4849

0 commit comments

Comments
 (0)