From 13f8fe1019b0d234d949985b053c9703af5c18fa Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Sat, 21 Nov 2026 16:26:39 +1000 Subject: [PATCH 1/4] fix: catch specific exceptions in Camera.clf and Image.choose Camera.clf swallowed any error from Artist.remove; only NotImplementedError (axes furniture) and ValueError (already removed) are expected. Image.choose now catches the TypeError and ValueError that getvector raises for a bad color. Co-Authored-By: Claude Sonnet 5.5 --- src/machinevisiontoolbox/Camera.py | 4 +++- src/machinevisiontoolbox/ImageProcessing.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) 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] From b6f834a0bb8c401b072c71d846edcfdaf0047bf8 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Sat, 21 Nov 2026 16:31:24 +1000 Subject: [PATCH 2/4] chore: exclude the book-code notebooks in tests/RVC from ruff Co-Authored-By: Claude Sonnet 5.5 --- pyproject.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index a59f44ca..165ac13a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -112,6 +112,8 @@ 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"] From fea9d19b884f50365cdf383359f8a731b624242a Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Sat, 21 Nov 2026 16:36:19 +1000 Subject: [PATCH 3/4] chore: narrow or explain every broad except, and enable ruff BLE Each remaining except Exception is now either narrowed to the exceptions that can occur or carries a noqa with the reason it is deliberately broad. Enables BLE in the ruff rules so new ones are flagged. Also fixes imtool's pixel readout, which left val unset for an unknown pixel type. Co-Authored-By: Claude Sonnet 5.5 --- pyproject.toml | 2 +- src/machinevisiontoolbox/Sources.py | 4 ++-- src/machinevisiontoolbox/bin/_iminteractive.py | 9 +++++---- src/machinevisiontoolbox/bin/imtool.py | 4 +++- src/machinevisiontoolbox/bin/mvtbtool.py | 6 +++--- tests/base/test_meshgrid.py | 4 ++-- tests/conftest.py | 4 ++-- tests/test_ros.py | 8 ++++---- 8 files changed, 22 insertions(+), 19 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 165ac13a..9903a09b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -116,7 +116,7 @@ line-length = 120 extend-exclude = ["tests/RVC"] [tool.ruff.lint] -select = ["E", "F", "I"] +select = ["E", "F", "I", "BLE"] [tool.ruff.lint.per-file-ignores] # these files re-export their submodules with star imports on purpose, so that 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..fc395702 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 - 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 - 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 - test cleanup must not fail whatever state the client is in pass stream.client.terminate = _safe_terminate From c6d76c352a4004a0c90ecdd50c0d430a3d97570b Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Sun, 22 Nov 2026 06:15:39 +1000 Subject: [PATCH 4/4] chore: enable ruff S110 and mark the deliberate try/except/pass sites Co-Authored-By: Claude Sonnet 5.5 --- pyproject.toml | 2 +- tests/test_ros.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 9903a09b..ab416dd5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -116,7 +116,7 @@ line-length = 120 extend-exclude = ["tests/RVC"] [tool.ruff.lint] -select = ["E", "F", "I", "BLE"] +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/tests/test_ros.py b/tests/test_ros.py index fc395702..9ea1aff6 100644 --- a/tests/test_ros.py +++ b/tests/test_ros.py @@ -817,7 +817,7 @@ async def _handler(self, websocket) -> None: topic = msg.get("topic", "") if t := tasks.pop(topic, None): t.cancel() - except Exception: # noqa: BLE001 - fake server: a client disconnect ends the handler quietly + 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: # noqa: BLE001 - fake server: a client disconnect ends the loop quietly + 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: # noqa: BLE001 - test cleanup must not fail whatever state the client is in + except Exception: # noqa: BLE001, S110 - test cleanup must not fail whatever state the client is in pass stream.client.terminate = _safe_terminate