From 33587451031e8380d7128411212a3933477f9714 Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Mon, 20 May 2024 17:43:54 -0700 Subject: [PATCH] ruff: enable UP old-commit-hash: b2e4c64cf8fe3256d1e411e8715c29e2eb6f4f00 --- common/api/__init__.py | 2 +- common/gpio.py | 4 ++-- common/spinner.py | 2 +- common/stat_live.py | 4 ++-- pyproject.toml | 3 ++- selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py | 2 +- selfdrive/controls/lib/pid.py | 2 +- selfdrive/controls/radard.py | 4 ++-- selfdrive/controls/tests/test_following_distance.py | 2 +- selfdrive/debug/vw_mqb_config.py | 2 +- selfdrive/locationd/models/car_kf.py | 2 +- selfdrive/locationd/models/live_kf.py | 4 ++-- selfdrive/modeld/modeld.py | 5 ++--- selfdrive/monitoring/driver_monitor.py | 8 ++++---- selfdrive/statsd.py | 4 ++-- selfdrive/test/longitudinal_maneuvers/plant.py | 2 +- selfdrive/test/process_replay/test_imgproc.py | 4 ++-- selfdrive/test/profiling/lib.py | 4 ++-- system/athena/tests/helpers.py | 6 +++--- system/loggerd/tests/loggerd_tests_common.py | 6 +++--- system/ubloxd/pigeond.py | 2 +- system/updated/casync/tar.py | 3 ++- system/version.py | 2 +- system/webrtc/tests/test_webrtcd.py | 2 +- tools/lib/api.py | 2 +- 25 files changed, 42 insertions(+), 41 deletions(-) diff --git a/common/api/__init__.py b/common/api/__init__.py index 79875023a2..f3a7d83842 100644 --- a/common/api/__init__.py +++ b/common/api/__init__.py @@ -7,7 +7,7 @@ from openpilot.system.version import get_version API_HOST = os.getenv('API_HOST', 'https://api.commadotai.com') -class Api(): +class Api: def __init__(self, dongle_id): self.dongle_id = dongle_id with open(Paths.persist_root()+'/comma/id_rsa') as f: diff --git a/common/gpio.py b/common/gpio.py index 68932cb87a..66b2adf438 100644 --- a/common/gpio.py +++ b/common/gpio.py @@ -1,5 +1,5 @@ import os -from functools import lru_cache +from functools import cache def gpio_init(pin: int, output: bool) -> None: try: @@ -35,7 +35,7 @@ def gpio_export(pin: int) -> None: except Exception: print(f"Failed to export gpio {pin}") -@lru_cache(maxsize=None) +@cache def get_irq_action(irq: int) -> list[str]: try: with open(f"/sys/kernel/irq/{irq}/actions") as f: diff --git a/common/spinner.py b/common/spinner.py index 43d4bb2cc2..dcf22641c4 100644 --- a/common/spinner.py +++ b/common/spinner.py @@ -3,7 +3,7 @@ import subprocess from openpilot.common.basedir import BASEDIR -class Spinner(): +class Spinner: def __init__(self): try: self.spinner_proc = subprocess.Popen(["./spinner"], diff --git a/common/stat_live.py b/common/stat_live.py index a91c1819bb..3901c448d8 100644 --- a/common/stat_live.py +++ b/common/stat_live.py @@ -1,6 +1,6 @@ import numpy as np -class RunningStat(): +class RunningStat: # tracks realtime mean and standard deviation without storing any data def __init__(self, priors=None, max_trackable=-1): self.max_trackable = max_trackable @@ -51,7 +51,7 @@ class RunningStat(): def params_to_save(self): return [self.M, self.S, self.n] -class RunningStatFilter(): +class RunningStatFilter: def __init__(self, raw_priors=None, filtered_priors=None, max_trackable=-1): self.raw_stat = RunningStat(raw_priors, -1) self.filtered_stat = RunningStat(filtered_priors, max_trackable) diff --git a/pyproject.toml b/pyproject.toml index e445df0479..ce3cf4b6c3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -184,7 +184,7 @@ build-backend = "poetry.core.masonry.api" # https://beta.ruff.rs/docs/configuration/#using-pyprojecttoml [tool.ruff] indent-width = 2 -lint.select = ["E", "F", "W", "PIE", "C4", "ISC", "NPY", "RUF008", "RUF100", "A", "B", "TID251"] +lint.select = ["E", "F", "W", "PIE", "C4", "ISC", "NPY", "UP", "RUF008", "RUF100", "A", "B", "TID251"] lint.ignore = [ "E741", "E402", @@ -193,6 +193,7 @@ lint.ignore = [ "B027", "B024", "NPY002", # new numpy random syntax is worse + "UP038", # (x, y) -> x|y for isinstance ] line-length = 160 target-version="py311" diff --git a/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py b/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py index 83ec3b3a13..ad60861088 100755 --- a/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py +++ b/selfdrive/controls/lib/lateral_mpc_lib/lat_mpc.py @@ -128,7 +128,7 @@ def gen_lat_ocp(): return ocp -class LateralMpc(): +class LateralMpc: def __init__(self, x0=None): if x0 is None: x0 = np.zeros(X_DIM) diff --git a/selfdrive/controls/lib/pid.py b/selfdrive/controls/lib/pid.py index f4ec7e5996..29c4d8bd46 100644 --- a/selfdrive/controls/lib/pid.py +++ b/selfdrive/controls/lib/pid.py @@ -4,7 +4,7 @@ from numbers import Number from openpilot.common.numpy_fast import clip, interp -class PIDController(): +class PIDController: def __init__(self, k_p, k_i, k_f=0., k_d=0., pos_limit=1e308, neg_limit=-1e308, rate=100): self._k_p = k_p self._k_i = k_i diff --git a/selfdrive/controls/radard.py b/selfdrive/controls/radard.py index 16c9e0635c..7420f666f7 100755 --- a/selfdrive/controls/radard.py +++ b/selfdrive/controls/radard.py @@ -2,7 +2,7 @@ import importlib import math from collections import deque -from typing import Any, Optional +from typing import Any import capnp from cereal import messaging, log, car @@ -208,7 +208,7 @@ class RadarD: self.ready = False - def update(self, sm: messaging.SubMaster, rr: Optional[car.RadarData]): + def update(self, sm: messaging.SubMaster, rr): self.ready = sm.seen['modelV2'] self.current_time = 1e-9*max(sm.logMonoTime.values()) diff --git a/selfdrive/controls/tests/test_following_distance.py b/selfdrive/controls/tests/test_following_distance.py index 5d60911805..89a575a9ad 100755 --- a/selfdrive/controls/tests/test_following_distance.py +++ b/selfdrive/controls/tests/test_following_distance.py @@ -32,7 +32,7 @@ def run_following_distance_simulation(v_lead, t_end=100.0, e2e=False, personalit log.LongitudinalPersonality.standard, log.LongitudinalPersonality.aggressive], [0,10,35])) # speed -class TestFollowingDistance(): +class TestFollowingDistance: def test_following_distance(self): v_lead = float(self.speed) simulation_steady_state = run_following_distance_simulation(v_lead, e2e=self.e2e, personality=self.personality) diff --git a/selfdrive/debug/vw_mqb_config.py b/selfdrive/debug/vw_mqb_config.py index 64bc2bc638..6df1e57ce3 100755 --- a/selfdrive/debug/vw_mqb_config.py +++ b/selfdrive/debug/vw_mqb_config.py @@ -139,7 +139,7 @@ if __name__ == "__main__": # so fib a little and say that same tester did the programming current_date = date.today() formatted_date = current_date.strftime('%y-%m-%d') - year, month, day = [int(part) for part in formatted_date.split('-')] + year, month, day = (int(part) for part in formatted_date.split('-')) prog_date = bytes([year, month, day]) uds_client.write_data_by_identifier(DATA_IDENTIFIER_TYPE.PROGRAMMING_DATE, prog_date) tester_num = uds_client.read_data_by_identifier(DATA_IDENTIFIER_TYPE.CALIBRATION_REPAIR_SHOP_CODE_OR_CALIBRATION_EQUIPMENT_SERIAL_NUMBER) diff --git a/selfdrive/locationd/models/car_kf.py b/selfdrive/locationd/models/car_kf.py index 1f3e447a19..87a93cdd0c 100755 --- a/selfdrive/locationd/models/car_kf.py +++ b/selfdrive/locationd/models/car_kf.py @@ -28,7 +28,7 @@ def _slice(n): return s -class States(): +class States: # Vehicle model params STIFFNESS = _slice(1) # [-] STEER_RATIO = _slice(1) # [-] diff --git a/selfdrive/locationd/models/live_kf.py b/selfdrive/locationd/models/live_kf.py index c4933a6129..0cc3eca61d 100755 --- a/selfdrive/locationd/models/live_kf.py +++ b/selfdrive/locationd/models/live_kf.py @@ -20,7 +20,7 @@ def numpy2eigenstring(arr): return f"(Eigen::VectorXd({len(arr)}) << {arr_str}).finished()" -class States(): +class States: ECEF_POS = slice(0, 3) # x, y and z in ECEF in meters ECEF_ORIENTATION = slice(3, 7) # quat for pose of phone in ecef ECEF_VELOCITY = slice(7, 10) # ecef velocity in m/s @@ -39,7 +39,7 @@ class States(): ACC_BIAS_ERR = slice(18, 21) -class LiveKalman(): +class LiveKalman: name = 'live' initial_x = np.array([3.88e6, -3.37e6, 3.76e6, diff --git a/selfdrive/modeld/modeld.py b/selfdrive/modeld/modeld.py index 35e2a29aa1..66563a3c1c 100755 --- a/selfdrive/modeld/modeld.py +++ b/selfdrive/modeld/modeld.py @@ -206,9 +206,8 @@ def main(demo=False): continue if abs(meta_main.timestamp_sof - meta_extra.timestamp_sof) > 10000000: - cloudlog.error("frames out of sync! main: {} ({:.5f}), extra: {} ({:.5f})".format( - meta_main.frame_id, meta_main.timestamp_sof / 1e9, - meta_extra.frame_id, meta_extra.timestamp_sof / 1e9)) + cloudlog.error(f"frames out of sync! main: {meta_main.frame_id} ({meta_main.timestamp_sof / 1e9:.5f}),\ + extra: {meta_extra.frame_id} ({meta_extra.timestamp_sof / 1e9:.5f})") else: # Use single camera diff --git a/selfdrive/monitoring/driver_monitor.py b/selfdrive/monitoring/driver_monitor.py index 9faa5f4d05..85cc19eb8b 100644 --- a/selfdrive/monitoring/driver_monitor.py +++ b/selfdrive/monitoring/driver_monitor.py @@ -15,7 +15,7 @@ EventName = car.CarEvent.EventName # We recommend that you do not change these numbers from the defaults. # ****************************************************************************************** -class DRIVER_MONITOR_SETTINGS(): +class DRIVER_MONITOR_SETTINGS: def __init__(self): self._DT_DMON = DT_DMON # ref (page15-16): https://eur-lex.europa.eu/legal-content/EN/TXT/PDF/?uri=CELEX:42018X1947&rid=2 @@ -102,7 +102,7 @@ def face_orientation_from_net(angles_desc, pos_desc, rpy_calib): yaw -= rpy_calib[2] return roll_net, pitch, yaw -class DriverPose(): +class DriverPose: def __init__(self, max_trackable): self.yaw = 0. self.pitch = 0. @@ -116,12 +116,12 @@ class DriverPose(): self.cfactor_pitch = 1. self.cfactor_yaw = 1. -class DriverBlink(): +class DriverBlink: def __init__(self): self.left_blink = 0. self.right_blink = 0. -class DriverStatus(): +class DriverStatus: def __init__(self, rhd_saved=False, settings=None, always_on=False): if settings is None: settings = DRIVER_MONITOR_SETTINGS() diff --git a/selfdrive/statsd.py b/selfdrive/statsd.py index 2f9149b096..2b5a7bb3a7 100755 --- a/selfdrive/statsd.py +++ b/selfdrive/statsd.py @@ -4,7 +4,7 @@ import zmq import time from pathlib import Path from collections import defaultdict -from datetime import datetime, timezone +from datetime import datetime, UTC from typing import NoReturn from openpilot.common.params import Params @@ -133,7 +133,7 @@ def main() -> NoReturn: # flush when started state changes or after FLUSH_TIME_S if (time.monotonic() > last_flush_time + STATS_FLUSH_TIME_S) or (sm['deviceState'].started != started_prev): result = "" - current_time = datetime.utcnow().replace(tzinfo=timezone.utc) + current_time = datetime.utcnow().replace(tzinfo=UTC) tags['started'] = sm['deviceState'].started for key, value in gauges.items(): diff --git a/selfdrive/test/longitudinal_maneuvers/plant.py b/selfdrive/test/longitudinal_maneuvers/plant.py index ac54967f88..daf7cec32b 100755 --- a/selfdrive/test/longitudinal_maneuvers/plant.py +++ b/selfdrive/test/longitudinal_maneuvers/plant.py @@ -83,7 +83,7 @@ class Plant: lead = log.RadarState.LeadData.new_message() lead.dRel = float(d_rel) - lead.yRel = float(0.0) + lead.yRel = 0.0 lead.vRel = float(v_rel) lead.aRel = float(a_lead - self.acceleration) lead.vLead = float(v_lead) diff --git a/selfdrive/test/process_replay/test_imgproc.py b/selfdrive/test/process_replay/test_imgproc.py index a980548baa..036f21b9e5 100755 --- a/selfdrive/test/process_replay/test_imgproc.py +++ b/selfdrive/test/process_replay/test_imgproc.py @@ -93,7 +93,7 @@ if __name__ == "__main__": if pix_hash != ref_hash: print("result changed! please check kernel") - print("ref: %s" % ref_hash) - print("new: %s" % pix_hash) + print(f"ref: {ref_hash}") + print(f"new: {pix_hash}") else: print("test passed") diff --git a/selfdrive/test/profiling/lib.py b/selfdrive/test/profiling/lib.py index 7f3b0126ff..93ba215386 100644 --- a/selfdrive/test/profiling/lib.py +++ b/selfdrive/test/profiling/lib.py @@ -8,7 +8,7 @@ class ReplayDone(Exception): pass -class SubSocket(): +class SubSocket: def __init__(self, msgs, trigger): self.i = 0 self.trigger = trigger @@ -28,7 +28,7 @@ class SubSocket(): return msg -class PubSocket(): +class PubSocket: def send(self, data): pass diff --git a/system/athena/tests/helpers.py b/system/athena/tests/helpers.py index 322e9d81dd..a0a9cccdc1 100644 --- a/system/athena/tests/helpers.py +++ b/system/athena/tests/helpers.py @@ -9,7 +9,7 @@ class MockResponse: self.status_code = status_code -class EchoSocket(): +class EchoSocket: def __init__(self, port): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind(('127.0.0.1', port)) @@ -34,7 +34,7 @@ class EchoSocket(): self.socket.close() -class MockApi(): +class MockApi: def __init__(self, dongle_id): pass @@ -42,7 +42,7 @@ class MockApi(): return "fake-token" -class MockWebsocket(): +class MockWebsocket: sock = socket.socket() def __init__(self, recv_queue, send_queue): diff --git a/system/loggerd/tests/loggerd_tests_common.py b/system/loggerd/tests/loggerd_tests_common.py index e8a6d031c4..15fd997eb8 100644 --- a/system/loggerd/tests/loggerd_tests_common.py +++ b/system/loggerd/tests/loggerd_tests_common.py @@ -28,12 +28,12 @@ def create_random_file(file_path: Path, size_mb: float, lock: bool = False, uplo if upload_xattr is not None: setxattr(str(file_path), uploader.UPLOAD_ATTR_NAME, upload_xattr) -class MockResponse(): +class MockResponse: def __init__(self, text, status_code): self.text = text self.status_code = status_code -class MockApi(): +class MockApi: def __init__(self, dongle_id): pass @@ -43,7 +43,7 @@ class MockApi(): def get_token(self): return "fake-token" -class MockApiIgnore(): +class MockApiIgnore: def __init__(self, dongle_id): pass diff --git a/system/ubloxd/pigeond.py b/system/ubloxd/pigeond.py index 21b3a86f97..5711992cfb 100755 --- a/system/ubloxd/pigeond.py +++ b/system/ubloxd/pigeond.py @@ -61,7 +61,7 @@ def get_assistnow_messages(token: bytes) -> list[bytes]: return msgs -class TTYPigeon(): +class TTYPigeon: def __init__(self): self.tty = serial.VTIMESerial(UBLOX_TTY, baudrate=9600, timeout=0) diff --git a/system/updated/casync/tar.py b/system/updated/casync/tar.py index 5c547e73a2..a5a8238bba 100644 --- a/system/updated/casync/tar.py +++ b/system/updated/casync/tar.py @@ -1,6 +1,7 @@ import pathlib import tarfile -from typing import IO, Callable +from typing import IO +from collections.abc import Callable def include_default(_) -> bool: diff --git a/system/version.py b/system/version.py index f5b8cd49e8..d258fe0492 100755 --- a/system/version.py +++ b/system/version.py @@ -27,7 +27,7 @@ def get_version(path: str = BASEDIR) -> str: def get_release_notes(path: str = BASEDIR) -> str: - with open(os.path.join(path, "RELEASES.md"), "r") as f: + with open(os.path.join(path, "RELEASES.md")) as f: return f.read().split('\n\n', 1)[0] diff --git a/system/webrtc/tests/test_webrtcd.py b/system/webrtc/tests/test_webrtcd.py index 684c7cf359..b0bc7b1966 100755 --- a/system/webrtc/tests/test_webrtcd.py +++ b/system/webrtc/tests/test_webrtcd.py @@ -20,7 +20,7 @@ from parameterized import parameterized_class ([], []), ]) @pytest.mark.asyncio -class TestWebrtcdProc(): +class TestWebrtcdProc: async def assertCompletesWithTimeout(self, awaitable, timeout=1): try: async with asyncio.timeout(timeout): diff --git a/tools/lib/api.py b/tools/lib/api.py index 6ff9242f29..92a75d2a3b 100644 --- a/tools/lib/api.py +++ b/tools/lib/api.py @@ -2,7 +2,7 @@ import os import requests API_HOST = os.getenv('API_HOST', 'https://api.commadotai.com') -class CommaApi(): +class CommaApi: def __init__(self, token=None): self.session = requests.Session() self.session.headers['User-agent'] = 'OpenpilotTools'