]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-131938: Update exception message for `Element.remove()` when an element is not...
authorBénédikt Tran <10796600+picnixz@users.noreply.github.com>
Fri, 4 Apr 2025 15:04:07 +0000 (17:04 +0200)
committerGitHub <noreply@github.com>
Fri, 4 Apr 2025 15:04:07 +0000 (15:04 +0000)
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".

Lib/test/test_xml_etree.py
Lib/xml/etree/ElementTree.py
Misc/NEWS.d/next/Library/2025-04-01-13-44-26.gh-issue-131938.dm4Suq.rst [new file with mode: 0644]
Modules/_elementtree.c

index 7f5945d8515fbaf0dd066331a6f2f5cbad6d4a3a..5fe9d6884106adcca3892ed3218e900297be4939 100644 (file)
@@ -344,9 +344,9 @@ class ElementTreeTest(unittest.TestCase):
         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 />')
index ce67d7d7d54748c98a66e8101bae3c14c4242a93..44ab5d18624e7330669fe297ecf3619d9803c6e4 100644 (file)
@@ -267,7 +267,11 @@ class Element:
 
         """
         # 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.
diff --git a/Misc/NEWS.d/next/Library/2025-04-01-13-44-26.gh-issue-131938.dm4Suq.rst b/Misc/NEWS.d/next/Library/2025-04-01-13-44-26.gh-issue-131938.dm4Suq.rst
new file mode 100644 (file)
index 0000000..6cc212e
--- /dev/null
@@ -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.
index f4f48538e30abedaa7427cbbf59f682dd4eed80c..bf221106c310632372a8002704728cd086edef1d 100644 (file)
@@ -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;
     }