gh-140601: Add ResourceWarning to iterparse when not closed (GH-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>
This commit is contained in:
Osama Abdelkader 2025-11-13 20:05:28 +01:00 committed by GitHub
parent 209eaff68c
commit a486d452c7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 69 additions and 4 deletions

View file

@ -1261,16 +1261,20 @@ def iterator(source):
gen = iterator(source)
class IterParseIterator(collections.abc.Iterator):
__next__ = gen.__next__
def close(self):
nonlocal close_source
if close_source:
source.close()
close_source = False
gen.close()
def __del__(self):
# TODO: Emit a ResourceWarning if it was not explicitly closed.
# (When the close() method will be supported in all maintained Python versions.)
def __del__(self, _warn=warnings.warn):
if close_source:
source.close()
try:
_warn(f"unclosed iterparse iterator {source.name!r}", ResourceWarning, stacklevel=2)
finally:
source.close()
it = IterParseIterator()
it.root = None