diff --git a/pyproject.toml b/pyproject.toml index a59f44ca..ab416dd5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -112,9 +112,11 @@ addopts = "--tb=short" [tool.ruff] line-length = 120 +# the notebooks that reproduce the book code have a bare except in their setup cell +extend-exclude = ["tests/RVC"] [tool.ruff.lint] -select = ["E", "F", "I"] +select = ["E", "F", "I", "BLE", "S110"] [tool.ruff.lint.per-file-ignores] # these files re-export their submodules with star imports on purpose, so that diff --git a/src/machinevisiontoolbox/Camera.py b/src/machinevisiontoolbox/Camera.py index 2820c3bb..569ef6a9 100644 --- a/src/machinevisiontoolbox/Camera.py +++ b/src/machinevisiontoolbox/Camera.py @@ -841,7 +841,9 @@ def clf(self) -> None: for artist in self._ax.get_children(): try: artist.remove() - except Exception: + except (NotImplementedError, ValueError): + # axes furniture (spines, axes, text, patches) cannot be removed, + # and an artist that was already removed raises ValueError pass def plot_point( diff --git a/src/machinevisiontoolbox/ImageProcessing.py b/src/machinevisiontoolbox/ImageProcessing.py index cab307c0..79fe9862 100644 --- a/src/machinevisiontoolbox/ImageProcessing.py +++ b/src/machinevisiontoolbox/ImageProcessing.py @@ -1133,7 +1133,7 @@ def choose(self, image2: Any, mask: Any) -> Self: else: try: color = argcheck.getvector(image2, 3) - except Exception: + except (TypeError, ValueError): raise ValueError("expecting a scalar, string or 3-vector") if self.isbgr: color = color[::-1] diff --git a/src/machinevisiontoolbox/Sources.py b/src/machinevisiontoolbox/Sources.py index 929ebcc8..ab27bdd2 100644 --- a/src/machinevisiontoolbox/Sources.py +++ b/src/machinevisiontoolbox/Sources.py @@ -3612,7 +3612,7 @@ def _autodetect_typestore(self, rawdata: bytes, msgtype: str) -> bool: print( f" auto-detect: {name} (ros1) failed: {type(e).__name__}: {e}" ) - except Exception as e: + except Exception as e: # noqa: BLE001 - unexpected failures are reported (verbose), not fatal if self.verbose: print( f" auto-detect: {name} (ros1) UNEXPECTED {type(e).__name__}: {e}" @@ -3650,7 +3650,7 @@ def _autodetect_typestore(self, rawdata: bytes, msgtype: str) -> bool: f" auto-detect: {name} (CDR) failed: {type(e).__name__}: {e}" ) continue - except Exception as e: + except Exception as e: # noqa: BLE001 - unexpected failures are reported (verbose), not fatal if self.verbose: print( f" auto-detect: {name} (CDR) UNEXPECTED {type(e).__name__}: {e}" diff --git a/src/machinevisiontoolbox/bin/_iminteractive.py b/src/machinevisiontoolbox/bin/_iminteractive.py index 26ed7748..5cc1519d 100644 --- a/src/machinevisiontoolbox/bin/_iminteractive.py +++ b/src/machinevisiontoolbox/bin/_iminteractive.py @@ -165,7 +165,8 @@ def _toolbar_active(self) -> bool: try: mode = str(self._fig.canvas.manager.toolbar.mode) return bool(mode) - except Exception: + except AttributeError: + # the backend has no toolbar (or no window manager) return False def _norm_rect(self): @@ -409,7 +410,7 @@ def _defer(self, fn) -> None: def _fire(): try: fn() - except Exception: + except Exception: # noqa: BLE001 - never let an error escape into the GUI event loop import traceback traceback.print_exc() @@ -435,7 +436,7 @@ def _popup_hist(self, roi, *, cumulative: bool) -> None: ) # keep Python Figure alive (timer closure guard) _guard_popup_close(fig) fig.show() - except Exception: + except Exception: # noqa: BLE001 - never let an error escape into the GUI event loop import traceback traceback.print_exc() @@ -450,7 +451,7 @@ def _popup_roi(self, roi) -> None: ) # keep Python Figure alive (timer closure guard) _guard_popup_close(fig) fig.show() - except Exception: + except Exception: # noqa: BLE001 - never let an error escape into the GUI event loop import traceback traceback.print_exc() diff --git a/src/machinevisiontoolbox/bin/imtool.py b/src/machinevisiontoolbox/bin/imtool.py index 2ad1e465..fb6996f4 100755 --- a/src/machinevisiontoolbox/bin/imtool.py +++ b/src/machinevisiontoolbox/bin/imtool.py @@ -209,6 +209,7 @@ def format_coord(u: float, v: float) -> str: val = f"{x}" else: print(f"unknown pixel type {type(x)}") + val = str(x) return f"({u}, {v}): {val}" else: @@ -223,7 +224,8 @@ def format_coord(u: float, v: float) -> str: val = "[" + ", ".join(parts) + "]" return f"({u}, {v}): {val} {colorspace}, {x.dtype}" - except Exception as e: + except IndexError: + # the cursor is outside the image return "bad" diff --git a/src/machinevisiontoolbox/bin/mvtbtool.py b/src/machinevisiontoolbox/bin/mvtbtool.py index 0a829ca6..fbc9f803 100755 --- a/src/machinevisiontoolbox/bin/mvtbtool.py +++ b/src/machinevisiontoolbox/bin/mvtbtool.py @@ -295,7 +295,7 @@ def run_smoke_test() -> bool: smoothed.array, img.array ) checks.append(("Image.Read + smooth() (OpenCV-backed)", ok)) - except Exception as e: + except Exception as e: # noqa: BLE001 - a self-check reports any failure, it must not crash checks.append((f"Image.Read + smooth() (OpenCV-backed): {e}", False)) try: @@ -310,7 +310,7 @@ def run_smoke_test() -> bool: voxels = bunny.voxel_grid(voxel_size=0.01) ok = len(bunny) > 0 and len(voxels._voxels.get_voxels()) > 0 checks.append(("PointCloud.Read('bunny.ply') + voxel_grid() (Open3D-backed)", ok)) - except Exception as e: + except Exception as e: # noqa: BLE001 - a self-check reports any failure, it must not crash checks.append( (f"PointCloud.Read('bunny.ply') + voxel_grid() (Open3D-backed): {e}", False) ) @@ -426,7 +426,7 @@ def out_prompt_tokens(self, cli=None): print(Fore.yellow) print(f"%run -i {args.run}") code.append(f"%run -i '{args.run}'") - except Exception as e: + except Exception as e: # noqa: BLE001 - report any failure and fall back to a bare IPython session if _colored: print(Fore.red) print(f"Error loading images or running script: {e}") diff --git a/tests/base/test_meshgrid.py b/tests/base/test_meshgrid.py index 852037f6..21c4ade2 100644 --- a/tests/base/test_meshgrid.py +++ b/tests/base/test_meshgrid.py @@ -29,8 +29,8 @@ def load_meshgrid_module(): try: exec(source_code, namespace) - except Exception as e: - raise ImportError(f"Failed to load meshgrid module: {e}") + except Exception as e: # noqa: BLE001 - whatever goes wrong, report it as a failure to load + raise ImportError(f"Failed to load meshgrid module: {e}") from e return namespace diff --git a/tests/conftest.py b/tests/conftest.py index 2337b164..cd65346c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -45,7 +45,7 @@ def _suppress_gui(monkeypatch): monkeypatch.setattr(cv2, "destroyWindow", lambda *args, **kwargs: None) if hasattr(cv2, "destroyAllWindows"): monkeypatch.setattr(cv2, "destroyAllWindows", lambda *args, **kwargs: None) - except Exception: + except ImportError: pass try: @@ -55,5 +55,5 @@ def _suppress_gui(monkeypatch): import matplotlib.pyplot as plt monkeypatch.setattr(plt, "show", lambda *args, **kwargs: None) - except Exception: + except ImportError: pass diff --git a/tests/test_ros.py b/tests/test_ros.py index e4f8f4a1..9ea1aff6 100644 --- a/tests/test_ros.py +++ b/tests/test_ros.py @@ -740,7 +740,7 @@ async def _serve() -> None: try: self._loop.run_until_complete(_serve()) - except Exception: + except Exception: # noqa: BLE001 - fake server: any startup failure just unblocks the caller self._ready.set() # unblock caller if startup failed # --- message builders ------------------------------------------------ @@ -817,7 +817,7 @@ async def _handler(self, websocket) -> None: topic = msg.get("topic", "") if t := tasks.pop(topic, None): t.cancel() - except Exception: + except Exception: # noqa: BLE001, S110 - fake server: a client disconnect ends the handler quietly pass finally: for task in tasks.values(): @@ -840,7 +840,7 @@ async def _publish_loop( await asyncio.sleep(interval) except asyncio.CancelledError: pass - except Exception: + except Exception: # noqa: BLE001, S110 - fake server: a client disconnect ends the loop quietly pass @@ -913,7 +913,7 @@ def _safe_terminate() -> None: try: if stream.client.is_connected: stream.client.close() - except Exception: + except Exception: # noqa: BLE001, S110 - test cleanup must not fail whatever state the client is in pass stream.client.terminate = _safe_terminate