Skip to content

Commit 04bc681

Browse files
authored
gh-131938: Update exception message for Element.remove() when an element is not found (#131972)
The exception message for `xml.etree.ElementTree.Element.remove` when an element is not found has been updated from "list.remove(x): x not in list" to "Element.remove(x): element not found".
1 parent df59226 commit 04bc681

File tree

4 files changed

+12
-4
lines changed

4 files changed

+12
-4
lines changed

Lib/test/test_xml_etree.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -344,9 +344,9 @@ def test_simpleops(self):
344344
self.serialize_check(element, '<tag key="value"><subtag /></tag>') # 4
345345
element.remove(subelement)
346346
self.serialize_check(element, '<tag key="value" />') # 5
347-
with self.assertRaises(ValueError) as cm:
347+
with self.assertRaisesRegex(ValueError,
348+
r'Element\.remove\(.+\): element not found'):
348349
element.remove(subelement)
349-
self.assertEqual(str(cm.exception), 'list.remove(x): x not in list')
350350
self.serialize_check(element, '<tag key="value" />') # 6
351351
element[0:0] = [subelement, subelement, subelement]
352352
self.serialize_check(element[1], '<subtag />')

Lib/xml/etree/ElementTree.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,11 @@ def remove(self, subelement):
267267
268268
"""
269269
# assert iselement(element)
270-
self._children.remove(subelement)
270+
try:
271+
self._children.remove(subelement)
272+
except ValueError:
273+
# to align the error message with the C implementation
274+
raise ValueError("Element.remove(x): element not found") from None
271275

272276
def find(self, path, namespaces=None):
273277
"""Find first matching element by tag name or path.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:mod:`xml.etree.ElementTree`: update the error message when an element to
2+
remove via :meth:`Element.remove <xml.etree.ElementTree.Element.remove>` is
3+
not found. Patch by Bénédikt Tran.

Modules/_elementtree.c

+2-1
Original file line numberDiff line numberDiff line change
@@ -1654,7 +1654,8 @@ _elementtree_Element_remove_impl(ElementObject *self, PyObject *subelement)
16541654
}
16551655

16561656
if (rc == 0) {
1657-
PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
1657+
PyErr_SetString(PyExc_ValueError,
1658+
"Element.remove(x): element not found");
16581659
return NULL;
16591660
}
16601661

0 commit comments

Comments
 (0)