Skip to content

fix: use context manager for file operations in cardiology_detect.py (Fixes #1171)#1172

Open
rtmalikian wants to merge 1 commit into
sunlabuiuc:masterfrom
rtmalikian:fix/issue-stacklevel-and-resource-leaks
Open

fix: use context manager for file operations in cardiology_detect.py (Fixes #1171)#1172
rtmalikian wants to merge 1 commit into
sunlabuiuc:masterfrom
rtmalikian:fix/issue-stacklevel-and-resource-leaks

Conversation

@rtmalikian

Copy link
Copy Markdown

Fixes #1171

Problem

pyhealth/tasks/cardiology_detect.py uses bare open().readlines() calls in 5 places. These rely on CPython's reference counting for file handle cleanup, which is not guaranteed behavior across all Python implementations.

Root Cause

The original code uses the pattern:

label_content = open(os.path.join(root, label), "r").readlines()

This leaves the file handle cleanup to garbage collection rather than explicit resource management.

Solution

Replaced all 5 occurrences with with open() as f: context managers:

with open(os.path.join(root, label), "r") as f:
    label_content = f.readlines()

Verification

  • grep -c "= open(" pyhealth/tasks/cardiology_detect.py → 0 (all bare open calls removed)
  • ast.parse(): syntax check passes
  • git diff: 10 insertions, 5 deletions across 5 sites

Changelog

Date Change Author
2026-07-01 Replace 5 bare open() calls with context managers rtmalikian

Files Changed

  • pyhealth/tasks/cardiology_detect.py — Wrapped 5 open().readlines() calls in with statements

Verification

  • 0 bare open() calls remaining in the file
  • Syntax check: ast.parse() passes

About the Author: Raphael Malikian — Clinical AI Solutions Architect. I specialise in building and fixing AI/ML systems for healthcare, including vector databases, RAG pipelines, and clinical NLP. If you need help with your project or think I can add value to your organisation, feel free to reach out — I'd love to connect.

📧 rtmalikian@gmail.com
🔗 GitHub: https://github.com/rtmalikian
🔗 LinkedIn: http://www.linkedin.com/in/raphael-t-malikian-mbbs-bsc-hons-71075436a


Disclosure: This code was developed with assistance from DeepSeek-V4 (DeepSeek) via Hermes Agent (Nous Research). All changes were reviewed, tested against the actual codebase, and verified for correctness.

Replace 5 bare open().readlines() calls with 'with open() as f'
context managers to ensure proper file handle cleanup.

The previous pattern relied on CPython reference counting for
cleanup, which is not guaranteed across all Python implementations.

Signed-off-by: rtmalikian <rtmalikian@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: replace bare open() calls with context managers in cardiology_detect.py

1 participant