Repository navigation
xml.etree.ElementTree.iterparse() should emit ResourceWarning when not explicitly closed #140601
Copy link
Copy link
Closed
Closed
Copy link
Labels
stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytopic-XMLtype-featureA feature request or enhancementA feature request or enhancement
Description
Activity
- addedtype-featureA feature request or enhancementA feature request or enhancement
on Oct 25, 2025 - added 5 commits that reference this issue
on Oct 25, 2025 - addedstdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directory
on Oct 25, 2025 - added 3 commits that reference this issue
on Nov 13, 2025 Thank you for your contribution @osamakader.
Many thanks @serhiy-storchaka for your support.
- added 3 commits that reference this issue
on Dec 23, 2025
Metadata
Metadata
Assignees
Labels
stdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytopic-XMLtype-featureA feature request or enhancementA feature request or enhancement
Feature or enhancement
Proposal:
Description
The
iterparse()function inxml.etree.ElementTreehas a TODO comment (line 1270) requesting that aResourceWarningbe emitted when the iterator is garbage collected without being explicitly closed:The
close()method has been available for many years now, so this TODO can be implemented.Problem
When
iterparse()opens a file by filename (rather than accepting a pre-opened file object), it manages the file internally. If the iterator is not explicitly closed, the file handle remains open until garbage collection, which can lead to:Currently, no warning is issued to alert developers of this problem.
Proposed Solution
Implement the TODO by:
_closedflag to track whetherclose()has been calledResourceWarningin__del__()if the iterator was not closed and had opened a file internally (close_source == True)iterparse()opened the file itself (filename passed), not when a file object was providedExample
Current behavior (no warning):
Expected behavior (with fix):
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
No response
Linked PRs