Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: close file handles with context managers and enforce Ruff SIM115 (#5367)

Alex284aa62c2629
diff --git a/docs/export_support/harness.py b/docs/export_support/harness.py
index 1fcd721cf..7928e5412 100644
--- a/docs/export_support/harness.py
+++ b/docs/export_support/harness.py
@@ -406,7 +406,8 @@ def prepare_resume(cases: list[dict[str, Any]], out_json: str) -> dict[str, dict
done: dict[str, dict[str, Any]] = {}
if os.path.exists(out_json):
try:
- done = {r["name"]: r for r in json.load(open(out_json))}
+ with open(out_json) as fh:
+ done = {r["name"]: r for r in json.load(fh)}
except Exception:
done = {}
inv = load_inventory(out_json)
@@ -416,7 +417,8 @@ def prepare_resume(cases: list[dict[str, Any]], out_json: str) -> dict[str, dict
print(f"{out_json}: records are from {was}, starting over", flush=True)
done = {}
os.makedirs(os.path.dirname(os.path.abspath(out_json)), exist_ok=True)
- json.dump({"names": [c["name"] for c in cases], **stamp}, open(inventory_path(out_json), "w"), indent=1)
+ with open(inventory_path(out_json), "w") as fh:
+ json.dump({"names": [c["name"] for c in cases], **stamp}, fh, indent=1)
return done
@@ -434,15 +436,17 @@ def run_cases(cases: list[dict[str, Any]], out_json: str, only: list[str] | None
results.append(done[c["name"]])
continue
# mark as crashed first so a hard crash (segfault) is visible after restart
- json.dump(
- results + [{"name": c["name"], "group": c["group"], "status": "crashed", "note": c["note"]}],
- open(out_json, "w"),
- indent=1,
- default=str,
- )
+ with open(out_json, "w") as fh:
+ json.dump(
+ results + [{"name": c["name"], "group": c["group"], "status": "crashed", "note": c["note"]}],
+ fh,
+ indent=1,
+ default=str,
+ )
rec = run_case(c)
results.append(rec)
- json.dump(results, open(out_json, "w"), indent=1, default=str)
+ with open(out_json, "w") as fh:
+ json.dump(results, fh, indent=1, default=str)
extra = rec.get("error", "")
if rec["status"] == "ok" and rec.get("dropped_inputs"):
extra = f"inputs folded away: {rec['dropped_inputs']}"
@@ -456,12 +460,13 @@ def run_cases(cases: list[dict[str, Any]], out_json: str, only: list[str] | None
for r in results:
merged[r["name"]] = r
order = [c["name"] for c in cases]
- json.dump(
- [merged[n] for n in order if n in merged] + [r for n, r in merged.items() if n not in order],
- open(out_json, "w"),
- indent=1,
- default=str,
- )
+ with open(out_json, "w") as fh:
+ json.dump(
+ [merged[n] for n in order if n in merged] + [r for n, r in merged.items() if n not in order],
+ fh,
+ indent=1,
+ default=str,
+ )
from collections import Counter
print("SUMMARY", dict(Counter(r["status"] for r in results)), flush=True)
diff --git a/docs/export_support/merge.py b/docs/export_support/merge.py
index 6f86d8394..bce8b7a1f 100644
--- a/docs/export_support/merge.py
+++ b/docs/export_support/merge.py
@@ -254,7 +254,9 @@ def _load_results(pattern: str) -> dict[str, dict]:
"""
out: dict[str, dict] = {}
for f in sorted(glob.glob(pattern)):
- for r in json.load(open(f)):
+ with open(f) as fh:
+ rows = json.load(fh)
+ for r in rows:
bogus = "crashed" in (r.get("export"), r.get("status")) or "PythonDispatcherTLS" in str(r.get("error", ""))
if bogus and r["name"] in out:
continue
@@ -281,7 +283,8 @@ def _validate(patterns: list[str], force: bool) -> dict[str, str]:
problems.append(f"{f}: no {Path(inventory_path(f)).name} next to it (rerun the probe)")
continue
stamps.setdefault((inv.get("revision", "?"), inv.get("torch", "?")), []).append(Path(f).name)
- have = {r["name"] for r in json.load(open(f)) if "crashed" not in (r.get("status"), r.get("export"))}
+ with open(f) as fh:
+ have = {r["name"] for r in json.load(fh) if "crashed" not in (r.get("status"), r.get("export"))}
missing = [n for n in inv["names"] if n not in have]
if missing:
problems.append(f"{f}: {len(missing)} of {len(inv['names'])} cases have no record, e.g. {missing[:3]}")
diff --git a/docs/export_support/probe_compile.py b/docs/export_support/probe_compile.py
index fd4281a83..b1a8a0418 100644
--- a/docs/export_support/probe_compile.py
+++ b/docs/export_support/probe_compile.py
@@ -200,23 +200,26 @@ def main() -> None:
results.append(done[c["name"]])
continue
# write a crash marker first so a hard crash (segfault, OOM) is visible on resume
- json.dump(
- results + [{"name": c["name"], "group": c["group"], "export": "crashed", "compile": "crashed"}],
- open(out_json, "w"),
- indent=1,
- default=str,
- )
+ with open(out_json, "w") as fh:
+ json.dump(
+ results + [{"name": c["name"], "group": c["group"], "export": "crashed", "compile": "crashed"}],
+ fh,
+ indent=1,
+ default=str,
+ )
try:
rec = run_case(c)
except Poisoned:
# drop the crash marker, keep what is done and let the caller start a fresh interpreter
kept = {r["name"]: r for r in done.values()} if only else {}
kept.update({r["name"]: r for r in results})
- json.dump(list(kept.values()), open(out_json, "w"), indent=1, default=str)
+ with open(out_json, "w") as fh:
+ json.dump(list(kept.values()), fh, indent=1, default=str)
print(f"{c['name']}: interpreter poisoned by an earlier case, exiting for a restart", flush=True)
sys.exit(POISON_EXIT)
results.append(rec)
- json.dump(results, open(out_json, "w"), indent=1, default=str)
+ with open(out_json, "w") as fh:
+ json.dump(results, fh, indent=1, default=str)
print(
f"{rec['name']:48s} export={rec.get('export'):8s} compile={rec.get('compile'):14s} "
f"{rec.get('export_s', ''):>6} {rec.get('compile_s', ''):>6} "
@@ -228,7 +231,8 @@ def main() -> None:
for r in results:
merged[r["name"]] = r
order = [c["name"] for c in cases]
- json.dump([merged[n] for n in order if n in merged], open(out_json, "w"), indent=1, default=str)
+ with open(out_json, "w") as fh:
+ json.dump([merged[n] for n in order if n in merged], fh, indent=1, default=str)
from collections import Counter
print(
diff --git a/kornia/core/download.py b/kornia/core/download.py
index c4e77ae2b..5e2570b5b 100644
--- a/kornia/core/download.py
+++ b/kornia/core/download.py
@@ -666,7 +666,8 @@ def _download_url_to_file(
for _ in range(tempfile.TMP_MAX):
partial = f"{dst}.{uuid.uuid4().hex}.partial"
try:
- f = open(partial, "xb")
+ # Opened outside ``with`` so a taken name can be retried; ``with f:`` below closes it.
+ f = open(partial, "xb") # noqa: SIM115
except FileExistsError:
continue
break
diff --git a/pyproject.toml b/pyproject.toml
index 23f35ddb7..6bdead75d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -226,6 +226,7 @@ select = [
"RSE", # flake8-raise
"RUF", # Ruff-specific rules
"S", # flake8-bandit
+ "SIM115", # open-file-with-context-handler
"SIM222", # expr-or-true
"SIM910", # dict-get-with-none-default
"SLOT", # flake8-slots