python / python/cpython

xml.dom.pulldom.DOMEventStream leaks file handles opened by parse()

Aberta
#148,428 1 comentário 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

stdlib topic-XML type-bug
Linguagem predominante
Python
Estrelas
77.2k
Forks
35.9k
Métricas de merge de PRs
Métricas de PR pendentes

Descrição

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

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Comece com DOMEventStream e pulldom.parse(), depois inspecione test_pulldom.py, especialmente a limpeza existente por volta da linha 36. Reproduza a ResourceWarning e verifique o comportamento de ownership para filename e os streams fornecidos pelo usuário. Considera-se concluído quando a limpeza do ciclo de vida e o comportamento do gerenciador de contexto estiverem cobertos por testes sem vazamento de handles.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
python
Domínio
backend
Tipo de issue
Bug
Dificuldade
3/5
Tempo estimado
1-2 dias
Status de atividade
Estagnada
Clareza
Claramente especificada
Facilidade para iniciantes
35/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.