diff options
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/test/test_xml_etree.py | 8 | ||||
-rw-r--r-- | Lib/xml/etree/ElementTree.py | 16 |
2 files changed, 17 insertions, 7 deletions
diff --git a/Lib/test/test_xml_etree.py b/Lib/test/test_xml_etree.py index 35d901f..d2bdc4f 100644 --- a/Lib/test/test_xml_etree.py +++ b/Lib/test/test_xml_etree.py @@ -658,6 +658,14 @@ class ElementTreeTest(unittest.TestCase): 'junk after document element: line 1, column 12') del cm, it + # Not exhausting the iterator still closes the resource (bpo-43292) + with warnings_helper.check_no_resource_warning(self): + it = iterparse(TESTFN) + del it + + with self.assertRaises(FileNotFoundError): + iterparse("nonexistent") + def test_writefile(self): elem = ET.Element("tag") elem.text = "text" diff --git a/Lib/xml/etree/ElementTree.py b/Lib/xml/etree/ElementTree.py index 6059e2f..5249c7a 100644 --- a/Lib/xml/etree/ElementTree.py +++ b/Lib/xml/etree/ElementTree.py @@ -1244,8 +1244,14 @@ def iterparse(source, events=None, parser=None): # Use the internal, undocumented _parser argument for now; When the # parser argument of iterparse is removed, this can be killed. pullparser = XMLPullParser(events=events, _parser=parser) - def iterator(): + + def iterator(source): + close_source = False try: + if not hasattr(source, "read"): + source = open(source, "rb") + close_source = True + yield None while True: yield from pullparser.read_events() # load event buffer @@ -1261,16 +1267,12 @@ def iterparse(source, events=None, parser=None): source.close() class IterParseIterator(collections.abc.Iterator): - __next__ = iterator().__next__ + __next__ = iterator(source).__next__ it = IterParseIterator() it.root = None del iterator, IterParseIterator - close_source = False - if not hasattr(source, "read"): - source = open(source, "rb") - close_source = True - + next(it) return it |