Skip to content

gh-131938: Update error message for Element.remove() when an element is not found #131972

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Lib/test/test_xml_etree.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,9 +344,9 @@ def test_simpleops(self):
self.serialize_check(element, '<tag key="value"><subtag /></tag>') # 4
element.remove(subelement)
self.serialize_check(element, '<tag key="value" />') # 5
with self.assertRaises(ValueError) as cm:
with self.assertRaisesRegex(ValueError,
r'Element\.remove\(.+\): element not found'):
element.remove(subelement)
self.assertEqual(str(cm.exception), 'list.remove(x): x not in list')
self.serialize_check(element, '<tag key="value" />') # 6
element[0:0] = [subelement, subelement, subelement]
self.serialize_check(element[1], '<subtag />')
Expand Down
6 changes: 5 additions & 1 deletion Lib/xml/etree/ElementTree.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,11 @@ def remove(self, subelement):
"""
# assert iselement(element)
self._children.remove(subelement)
try:
self._children.remove(subelement)
except ValueError:
# to align the error message with the C implementation
raise ValueError("Element.remove(x): element not found") from None

def find(self, path, namespaces=None):
"""Find first matching element by tag name or path.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:mod:`xml.etree.ElementTree`: update the error message when an element to
remove via :meth:`Element.remove <xml.etree.ElementTree.Element.remove>` is
not found. Patch by Bénédikt Tran.
3 changes: 2 additions & 1 deletion Modules/_elementtree.c
Original file line number Diff line number Diff line change
Expand Up @@ -1654,7 +1654,8 @@ _elementtree_Element_remove_impl(ElementObject *self, PyObject *subelement)
}

if (rc == 0) {
PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
PyErr_SetString(PyExc_ValueError,
"Element.remove(x): element not found");
return NULL;
}

Expand Down
Loading