◐ Shell
clean mode source ↗

gh-140601: Add ResourceWarning to iterparse when not closed by osamakader · Pull Request #140603 · python/cpython

When iterparse() opens a file by filename and is not explicitly closed,
emit a ResourceWarning to alert developers of the resource leak.

This implements the TODO comment at line 1270 of ElementTree.py which
has been requesting this feature since the close() method was added.

- Add _closed flag to IterParseIterator to track state
- Emit ResourceWarning in __del__ if not closed
- Add comprehensive test cases
- Update existing tests to properly close iterators

Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>

ashm-dev

ashm-dev

serhiy-storchaka

- Use nonlocal close_source instead of _closed flag
- Bind warnings.warn as default parameter in __del__
- Use assertWarns(ResourceWarning) instead of adding close() calls
- Use support.gc_collect() for consistent test behavior
- Remove broad exception handling

Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>

serhiy-storchaka

F-strings can fail during cleanup. Use % formatting like
subprocess.Popen does for safer __del__ behavior.

Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
Check that warning message contains 'unclosed file' and the
filename to ensure it's from iterparse, not the file destructor.

Addresses review feedback from serhiy-storchaka.

Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
The ResourceWarning tests are already covered in test_iterparse()
as noted by serhiy-storchaka in review.

Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
Removing source=self prevents unraisable exception in C extension.
The warning message still contains the filename via %r formatting.

Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
Document that iterparse now emits ResourceWarning in Python 3.15
when not explicitly closed.

Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>

cmaloney

ashm-dev

Co-authored-by: Cody Maloney <cmaloney@users.noreply.github.com>

CuriousLearner added a commit to CuriousLearner/cpython that referenced this pull request

Nov 13, 2025

CuriousLearner added a commit to CuriousLearner/cpython that referenced this pull request

Nov 14, 2025

CuriousLearner added a commit to CuriousLearner/cpython that referenced this pull request

Nov 14, 2025

StanFromIreland pushed a commit to StanFromIreland/cpython that referenced this pull request

Dec 6, 2025
…thonGH-140603)

When iterparse() opens a file by filename and is not explicitly closed,
emit a ResourceWarning to alert developers of the resource leak.

Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>