diff --git a/Lib/test/test_xml_etree.py b/Lib/test/test_xml_etree.py index acb11615b35c0b3..96626aa118cc465 100644 --- a/Lib/test/test_xml_etree.py +++ b/Lib/test/test_xml_etree.py @@ -4064,6 +4064,34 @@ def test_findall_wildcard(self): self.assertEqual(summarize_list(root.findall(".//{}b")), summarize_list(root.findall(".//b"))) + def do_test_find_empty_path(self, m): + # This tests the pure-Python ElementPath implementation; the C + # accelerator already returned the same results for most cases before + # gh-161807. After the fix both implementations agree. + + # Without namespaces + self.assertIsNone(m.find("")) + self.assertEqual(m.findall(""), []) + self.assertIsNone(m.findtext("")) + self.assertEqual(m.findtext("", "default"), "default") + self.assertEqual(list(m.iterfind("")), []) + + # With namespaces — the dict must not be altered by any of the calls + ns = {"ns": "http://example.com"} + ns_before = dict(ns) + self.assertIsNone(m.find("", ns)) + self.assertEqual(m.findall("", ns), []) + self.assertIsNone(m.findtext("", namespaces=ns)) + self.assertEqual(m.findtext("", "default", namespaces=ns), "default") + self.assertEqual(list(m.iterfind("", ns)), []) + self.assertEqual(ns, ns_before) + + def test_find_empty_path(self): + # gh-161807: empty path must not raise TypeError + e = ET.XML(SAMPLE_XML) + self.do_test_find_empty_path(e) + self.do_test_find_empty_path(ET.ElementTree(e)) + def test_bad_find(self): e = ET.XML(SAMPLE_XML) with self.assertRaisesRegex(SyntaxError, 'cannot use absolute path'): diff --git a/Lib/xml/etree/ElementPath.py b/Lib/xml/etree/ElementPath.py index de1fd203ff6a0f6..ca41ef403fb6fd2 100644 --- a/Lib/xml/etree/ElementPath.py +++ b/Lib/xml/etree/ElementPath.py @@ -384,7 +384,7 @@ def iterfind(elem, path, namespaces=None): try: token = next() except StopIteration: - return + return iter(()) selector = [] while 1: try: diff --git a/Misc/NEWS.d/next/Library/2026-11-12-23-45-00.gh-issue-161807._IY0DOR6.rst b/Misc/NEWS.d/next/Library/2026-11-12-23-45-00.gh-issue-161807._IY0DOR6.rst new file mode 100644 index 000000000000000..f6a862abc317b0a --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-12-23-45-00.gh-issue-161807._IY0DOR6.rst @@ -0,0 +1,6 @@ +Fix :func:`xml.etree.ElementTree.Element.find`, +:func:`~xml.etree.ElementTree.Element.findall`, +:func:`~xml.etree.ElementTree.Element.findtext`, and +:func:`~xml.etree.ElementTree.Element.iterfind` raising :exc:`TypeError` +when called with an empty path string. They now return ``None``, ``[]``, +the default value, and an empty iterator, respectively.