xml.dom.pulldom.DOMEventStream leaks file handles opened by parse()
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- Python
- Star
- 77.2k
- Fork
- 35.9k
- Chỉ số merge pull request
- Chỉ số pull request đang chờ
Mô tả
pulldom.parse() opens a file when called with a filename string, but the resulting DOMEventStream never closes it. The class has no close() method, no context manager support, and clear() just sets self.stream = None without closing.
This produces ResourceWarning: unclosed file and can lead to file descriptor exhaustion in long-running processes.
The documentation example at https://docs.python.org/3/library/xml.dom.pulldom.html#module-xml.dom.pulldom shows:
doc = pulldom.parse('sales_items.xml')
for event, node in doc:
...
— with no cleanup, so users following the docs will hit this.
Reproduction
import warnings, tempfile, os, gc
from xml.dom import pulldom
warnings.simplefilter('always', ResourceWarning)
fd, path = tempfile.mkstemp(suffix='.xml')
os.write(fd, b'<root><item>test</item></root>')
os.close(fd)
events = pulldom.parse(path)
for event, node in events:
pass
# stream is still open after full iteration
print(f'stream.closed: {events.stream.closed}') # False
# clear() doesn't close it either
events.clear()
del events
gc.collect() # ResourceWarning: unclosed file ...
os.unlink(path)
The existing test in test_pulldom.py already works around this with self.addCleanup(handler.stream.close) (line 36), which further confirms the leak.
Suggested fix
Track whether parse() opened the file (vs. receiving a user-provided stream), then add close(), __enter__/__exit__, and __del__ with ResourceWarning to DOMEventStream. Update clear() to close owned streams.
This follows the same approach used for ElementTree.iterparse() (gh-140601).
Linked PRs
- gh-148437
Hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Hướng nghiên cứu
Bắt đầu với DOMEventStream và pulldom.parse(), sau đó kiểm tra test_pulldom.py, đặc biệt là phần dọn dẹp hiện có quanh dòng 36. Tái hiện ResourceWarning và xác minh hành vi ownership đối với filename và các stream do người dùng cung cấp. Được xem là hoàn tất khi các bài kiểm thử bao quát việc dọn dẹp vòng đời và hành vi của context manager mà không làm rò rỉ các handle.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Đánh giá
- Công nghệ
- python
- Lĩnh vực
- backend
- Loại issue
- Lỗi
- Độ khó
- 3/5
- Thời gian dự kiến
- 1-2 ngày
- Mức độ hoạt động
- Đình trệ
- Độ rõ ràng
- Đặc tả rõ ràng
- Mức phù hợp với người mới
- 35/100