[3.10] bpo-43292: Fix file leak in `ET.iterparse()` when not exhausted (GH-31696) by miss-islington · Pull Request #31721 · python/cpython

Expand Up @@ -1248,8 +1248,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 Expand All @@ -1265,16 +1271,12 @@ def iterator(): 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

Expand Down