mirror of
https://github.com/python/cpython.git
synced 2025-12-08 06:10:17 +00:00
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:
parent
209eaff68c
commit
a486d452c7
5 changed files with 69 additions and 4 deletions
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue