Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion src/machinevisiontoolbox/Camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion src/machinevisiontoolbox/ImageProcessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
4 changes: 2 additions & 2 deletions src/machinevisiontoolbox/Sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
Expand Down Expand Up @@ -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}"
Expand Down
9 changes: 5 additions & 4 deletions src/machinevisiontoolbox/bin/_iminteractive.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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()
Expand All @@ -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()
Expand All @@ -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()
Expand Down
4 changes: 3 additions & 1 deletion src/machinevisiontoolbox/bin/imtool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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"


Expand Down
6 changes: 3 additions & 3 deletions src/machinevisiontoolbox/bin/mvtbtool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
)
Expand Down Expand Up @@ -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}")
Expand Down
4 changes: 2 additions & 2 deletions tests/base/test_meshgrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
8 changes: 4 additions & 4 deletions tests/test_ros.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ------------------------------------------------
Expand Down Expand Up @@ -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():
Expand All @@ -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


Expand Down Expand Up @@ -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
Expand Down
Loading