diff options
author | Jacob Walls <jacobtylerwalls@gmail.com> | 2022-03-07 09:31:46 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-03-07 09:31:46 (GMT) |
commit | 496c428de3318c9c5770937491b71dc3d3f18a6a (patch) | |
tree | 1e08551d1648d11fa4c7bca40550b4701a5c2bd5 /Lib/xml | |
parent | b748a36696ca56ed4ffcfae011a8488878eb2b3a (diff) | |
download | cpython-496c428de3318c9c5770937491b71dc3d3f18a6a.zip cpython-496c428de3318c9c5770937491b71dc3d3f18a6a.tar.gz cpython-496c428de3318c9c5770937491b71dc3d3f18a6a.tar.bz2 |
bpo-43292: Fix file leak in `ET.iterparse()` when not exhausted (GH-31696)
Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
Diffstat (limited to 'Lib/xml')
-rw-r--r-- | Lib/xml/etree/ElementTree.py | 16 |
1 files changed, 9 insertions, 7 deletions
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 |