Skip to content

Commit

Permalink
Update linters, activate more ruff rules (#1669)
Browse files Browse the repository at this point in the history
* update ruff to 0.0.286

* activate pyflakes rules

* activate flake8-type-checking

* activate Ruff-specific rules

* activate pylint rules

* activate flake8-comprehensions

* update ruff to 0.0.292

* remove unnecessary tuple() call

* update mypy to 1.5.*, update black to 23.9.*

---------

Co-authored-by: zariiii9003 <[email protected]>
  • Loading branch information
zariiii9003 and zariiii9003 authored Oct 8, 2023
1 parent 3c3f123 commit 237f2be
Show file tree
Hide file tree
Showing 22 changed files with 133 additions and 140 deletions.
5 changes: 3 additions & 2 deletions can/bit_timing.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# pylint: disable=too-many-lines
import math
from typing import Iterator, List, Mapping, cast
from typing import TYPE_CHECKING, Iterator, List, Mapping, cast

from can.typechecking import BitTimingDict, BitTimingFdDict
if TYPE_CHECKING:
from can.typechecking import BitTimingDict, BitTimingFdDict


class BitTiming(Mapping):
Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/gs_usb.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def __init__(
"""
if (index is not None) and ((bus or address) is not None):
raise CanInitializationError(
f"index and bus/address cannot be used simultaneously"
"index and bus/address cannot be used simultaneously"
)

if index is not None:
Expand Down
18 changes: 9 additions & 9 deletions can/interfaces/ics_neovi/neovi_bus.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,15 +302,15 @@ def _find_device(self, type_filter=None, serial=None):
for device in devices:
if serial is None or self.get_serial_number(device) == str(serial):
return device
else:
msg = ["No device"]

if type_filter is not None:
msg.append(f"with type {type_filter}")
if serial is not None:
msg.append(f"with serial {serial}")
msg.append("found.")
raise CanInitializationError(" ".join(msg))

msg = ["No device"]

if type_filter is not None:
msg.append(f"with type {type_filter}")
if serial is not None:
msg.append(f"with serial {serial}")
msg.append("found.")
raise CanInitializationError(" ".join(msg))

def _process_msg_queue(self, timeout=0.1):
try:
Expand Down
18 changes: 9 additions & 9 deletions can/interfaces/ixxat/canlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,17 @@ def __init__(
unique_hardware_id: Optional[int] = None,
extended: bool = True,
fd: bool = False,
rx_fifo_size: int = None,
tx_fifo_size: int = None,
rx_fifo_size: Optional[int] = None,
tx_fifo_size: Optional[int] = None,
bitrate: int = 500000,
data_bitrate: int = 2000000,
sjw_abr: int = None,
tseg1_abr: int = None,
tseg2_abr: int = None,
sjw_dbr: int = None,
tseg1_dbr: int = None,
tseg2_dbr: int = None,
ssp_dbr: int = None,
sjw_abr: Optional[int] = None,
tseg1_abr: Optional[int] = None,
tseg2_abr: Optional[int] = None,
sjw_dbr: Optional[int] = None,
tseg1_dbr: Optional[int] = None,
tseg2_dbr: Optional[int] = None,
ssp_dbr: Optional[int] = None,
**kwargs,
):
"""
Expand Down
14 changes: 7 additions & 7 deletions can/interfaces/ixxat/canlib_vcinpl2.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,13 +436,13 @@ def __init__(
tx_fifo_size: int = 128,
bitrate: int = 500000,
data_bitrate: int = 2000000,
sjw_abr: int = None,
tseg1_abr: int = None,
tseg2_abr: int = None,
sjw_dbr: int = None,
tseg1_dbr: int = None,
tseg2_dbr: int = None,
ssp_dbr: int = None,
sjw_abr: Optional[int] = None,
tseg1_abr: Optional[int] = None,
tseg2_abr: Optional[int] = None,
sjw_dbr: Optional[int] = None,
tseg1_dbr: Optional[int] = None,
tseg2_dbr: Optional[int] = None,
ssp_dbr: Optional[int] = None,
**kwargs,
):
"""
Expand Down
104 changes: 47 additions & 57 deletions can/interfaces/pcan/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,73 +297,63 @@

# PCAN parameter values
#
PCAN_PARAMETER_OFF = int(0x00) # The PCAN parameter is not set (inactive)
PCAN_PARAMETER_ON = int(0x01) # The PCAN parameter is set (active)
PCAN_FILTER_CLOSE = int(0x00) # The PCAN filter is closed. No messages will be received
PCAN_FILTER_OPEN = int(
0x01
) # The PCAN filter is fully opened. All messages will be received
PCAN_FILTER_CUSTOM = int(
0x02
) # The PCAN filter is custom configured. Only registered messages will be received
PCAN_CHANNEL_UNAVAILABLE = int(
0x00
) # The PCAN-Channel handle is illegal, or its associated hardware is not available
PCAN_CHANNEL_AVAILABLE = int(
0x01
) # The PCAN-Channel handle is available to be connected (PnP Hardware: it means furthermore that the hardware is plugged-in)
PCAN_CHANNEL_OCCUPIED = int(
0x02
) # The PCAN-Channel handle is valid, and is already being used
PCAN_PARAMETER_OFF = 0x00 # The PCAN parameter is not set (inactive)
PCAN_PARAMETER_ON = 0x01 # The PCAN parameter is set (active)
PCAN_FILTER_CLOSE = 0x00 # The PCAN filter is closed. No messages will be received
PCAN_FILTER_OPEN = (
0x01 # The PCAN filter is fully opened. All messages will be received
)
PCAN_FILTER_CUSTOM = 0x02 # The PCAN filter is custom configured. Only registered messages will be received
PCAN_CHANNEL_UNAVAILABLE = 0x00 # The PCAN-Channel handle is illegal, or its associated hardware is not available
PCAN_CHANNEL_AVAILABLE = 0x01 # The PCAN-Channel handle is available to be connected (PnP Hardware: it means furthermore that the hardware is plugged-in)
PCAN_CHANNEL_OCCUPIED = (
0x02 # The PCAN-Channel handle is valid, and is already being used
)
PCAN_CHANNEL_PCANVIEW = (
PCAN_CHANNEL_AVAILABLE | PCAN_CHANNEL_OCCUPIED
) # The PCAN-Channel handle is already being used by a PCAN-View application, but is available to connect

LOG_FUNCTION_DEFAULT = int(0x00) # Logs system exceptions / errors
LOG_FUNCTION_ENTRY = int(0x01) # Logs the entries to the PCAN-Basic API functions
LOG_FUNCTION_PARAMETERS = int(
0x02
) # Logs the parameters passed to the PCAN-Basic API functions
LOG_FUNCTION_LEAVE = int(0x04) # Logs the exits from the PCAN-Basic API functions
LOG_FUNCTION_WRITE = int(0x08) # Logs the CAN messages passed to the CAN_Write function
LOG_FUNCTION_READ = int(
0x10
) # Logs the CAN messages received within the CAN_Read function
LOG_FUNCTION_ALL = int(
0xFFFF
) # Logs all possible information within the PCAN-Basic API functions
LOG_FUNCTION_DEFAULT = 0x00 # Logs system exceptions / errors
LOG_FUNCTION_ENTRY = 0x01 # Logs the entries to the PCAN-Basic API functions
LOG_FUNCTION_PARAMETERS = (
0x02 # Logs the parameters passed to the PCAN-Basic API functions
)
LOG_FUNCTION_LEAVE = 0x04 # Logs the exits from the PCAN-Basic API functions
LOG_FUNCTION_WRITE = 0x08 # Logs the CAN messages passed to the CAN_Write function
LOG_FUNCTION_READ = 0x10 # Logs the CAN messages received within the CAN_Read function
LOG_FUNCTION_ALL = (
0xFFFF # Logs all possible information within the PCAN-Basic API functions
)

TRACE_FILE_SINGLE = int(
0x00
) # A single file is written until it size reaches PAN_TRACE_SIZE
TRACE_FILE_SEGMENTED = int(
0x01
) # Traced data is distributed in several files with size PAN_TRACE_SIZE
TRACE_FILE_DATE = int(0x02) # Includes the date into the name of the trace file
TRACE_FILE_TIME = int(0x04) # Includes the start time into the name of the trace file
TRACE_FILE_OVERWRITE = int(
0x80
) # Causes the overwriting of available traces (same name)
TRACE_FILE_SINGLE = (
0x00 # A single file is written until it size reaches PAN_TRACE_SIZE
)
TRACE_FILE_SEGMENTED = (
0x01 # Traced data is distributed in several files with size PAN_TRACE_SIZE
)
TRACE_FILE_DATE = 0x02 # Includes the date into the name of the trace file
TRACE_FILE_TIME = 0x04 # Includes the start time into the name of the trace file
TRACE_FILE_OVERWRITE = 0x80 # Causes the overwriting of available traces (same name)

FEATURE_FD_CAPABLE = int(0x01) # Device supports flexible data-rate (CAN-FD)
FEATURE_DELAY_CAPABLE = int(
0x02
) # Device supports a delay between sending frames (FPGA based USB devices)
FEATURE_IO_CAPABLE = int(
0x04
) # Device supports I/O functionality for electronic circuits (USB-Chip devices)
FEATURE_FD_CAPABLE = 0x01 # Device supports flexible data-rate (CAN-FD)
FEATURE_DELAY_CAPABLE = (
0x02 # Device supports a delay between sending frames (FPGA based USB devices)
)
FEATURE_IO_CAPABLE = (
0x04 # Device supports I/O functionality for electronic circuits (USB-Chip devices)
)

SERVICE_STATUS_STOPPED = int(0x01) # The service is not running
SERVICE_STATUS_RUNNING = int(0x04) # The service is running
SERVICE_STATUS_STOPPED = 0x01 # The service is not running
SERVICE_STATUS_RUNNING = 0x04 # The service is running

# Other constants
#
MAX_LENGTH_HARDWARE_NAME = int(
33
) # Maximum length of the name of a device: 32 characters + terminator
MAX_LENGTH_VERSION_STRING = int(
256
) # Maximum length of a version string: 255 characters + terminator
MAX_LENGTH_HARDWARE_NAME = (
33 # Maximum length of the name of a device: 32 characters + terminator
)
MAX_LENGTH_VERSION_STRING = (
256 # Maximum length of a version string: 255 characters + terminator
)

# PCAN message types
#
Expand Down
6 changes: 3 additions & 3 deletions can/interfaces/pcan/pcan.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
boottimeEpoch = 0
else:
boottimeEpoch = uptime.boottime().timestamp()
except ImportError as error:
except ImportError:
log.warning(
"uptime library not available, timestamps are relative to boot time and not to Epoch UTC",
)
Expand Down Expand Up @@ -283,7 +283,7 @@ def __init__(
clock_param = "f_clock" if "f_clock" in kwargs else "f_clock_mhz"
fd_parameters_values = [
f"{key}={kwargs[key]}"
for key in (clock_param,) + PCAN_FD_PARAMETER_LIST
for key in (clock_param, *PCAN_FD_PARAMETER_LIST)
if key in kwargs
]

Expand Down Expand Up @@ -413,7 +413,7 @@ def bits(n):
def get_api_version(self):
error, value = self.m_objPCANBasic.GetValue(PCAN_NONEBUS, PCAN_API_VERSION)
if error != PCAN_ERROR_OK:
raise CanInitializationError(f"Failed to read pcan basic api version")
raise CanInitializationError("Failed to read pcan basic api version")

# fix https://github.com/hardbyte/python-can/issues/1642
version_string = value.decode("ascii").replace(",", ".").replace(" ", "")
Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/socketcand/socketcand.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def __init__(self, channel, host, port, can_filters=None, **kwargs):
)
self._tcp_send(f"< open {channel} >")
self._expect_msg("< ok >")
self._tcp_send(f"< rawmode >")
self._tcp_send("< rawmode >")
self._expect_msg("< ok >")
super().__init__(channel=channel, can_filters=can_filters, **kwargs)

Expand Down
2 changes: 1 addition & 1 deletion can/interfaces/systec/ucan.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ def init_hardware(self, serial=None, device_number=ANY_MODULE):
Initializes the device with the corresponding serial or device number.
:param int or None serial: Serial number of the USB-CANmodul.
:param int device_number: Device number (0 254, or :const:`ANY_MODULE` for the first device).
:param int device_number: Device number (0 - 254, or :const:`ANY_MODULE` for the first device).
"""
if not self._hw_is_initialized:
# initialize hardware either by device number or serial
Expand Down
18 changes: 8 additions & 10 deletions can/interfaces/vector/canlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,19 +69,17 @@
class VectorBus(BusABC):
"""The CAN Bus implemented for the Vector interface."""

deprecated_args = dict(
sjwAbr="sjw_abr",
tseg1Abr="tseg1_abr",
tseg2Abr="tseg2_abr",
sjwDbr="sjw_dbr",
tseg1Dbr="tseg1_dbr",
tseg2Dbr="tseg2_dbr",
)

@deprecated_args_alias(
deprecation_start="4.0.0",
deprecation_end="5.0.0",
**deprecated_args,
**{
"sjwAbr": "sjw_abr",
"tseg1Abr": "tseg1_abr",
"tseg2Abr": "tseg2_abr",
"sjwDbr": "sjw_dbr",
"tseg1Dbr": "tseg1_dbr",
"tseg2Dbr": "tseg2_dbr",
},
)
def __init__(
self,
Expand Down
8 changes: 4 additions & 4 deletions can/io/asc.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ def __init__(
self.internal_events_logged = False

def _extract_header(self) -> None:
for line in self.file:
line = line.strip()
for _line in self.file:
line = _line.strip()

datetime_match = re.match(
r"date\s+\w+\s+(?P<datetime_string>.+)", line, re.IGNORECASE
Expand Down Expand Up @@ -255,8 +255,8 @@ def _process_fd_can_frame(self, line: str, msg_kwargs: Dict[str, Any]) -> Messag
def __iter__(self) -> Generator[Message, None, None]:
self._extract_header()

for line in self.file:
line = line.strip()
for _line in self.file:
line = _line.strip()

trigger_match = re.match(
r"begin\s+triggerblock\s+\w+\s+(?P<datetime_string>.+)",
Expand Down
4 changes: 2 additions & 2 deletions can/io/trc.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ def __init__(

def _extract_header(self):
line = ""
for line in self.file:
line = line.strip()
for _line in self.file:
line = _line.strip()
if line.startswith(";$FILEVERSION"):
logger.debug("TRCReader: Found file version '%s'", line)
try:
Expand Down
8 changes: 5 additions & 3 deletions can/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@
import re
import sys
from datetime import datetime
from typing import Any, Dict, List, Sequence, Tuple, Union
from typing import TYPE_CHECKING, Any, Dict, List, Sequence, Tuple, Union

import can
from can.io import BaseRotatingLogger
from can.io.generic import MessageWriter
from can.util import cast_from_string

from . import Bus, BusState, Logger, SizedRotatingLogger
from .typechecking import CanFilter, CanFilters

if TYPE_CHECKING:
from can.io import BaseRotatingLogger
from can.io.generic import MessageWriter


def _create_base_argument_parser(parser: argparse.ArgumentParser) -> None:
"""Adds common options to an argument parser."""
Expand Down
5 changes: 2 additions & 3 deletions can/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,9 +190,8 @@ def load_config(
)

# Slightly complex here to only search for the file config if required
for cfg in config_sources:
if callable(cfg):
cfg = cfg(context)
for _cfg in config_sources:
cfg = _cfg(context) if callable(_cfg) else _cfg
# remove legacy operator (and copy to interface if not already present)
if "bustype" in cfg:
if "interface" not in cfg or not cfg["interface"]:
Expand Down
2 changes: 1 addition & 1 deletion can/viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ def parse_args(args: List[str]) -> Tuple:
scaling.append(float(t))

if scaling:
data_structs[key] = (struct.Struct(fmt),) + tuple(scaling)
data_structs[key] = (struct.Struct(fmt), *scaling)
else:
data_structs[key] = struct.Struct(fmt)

Expand Down
Loading

0 comments on commit 237f2be

Please sign in to comment.