Skip to content
Open
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
14 changes: 12 additions & 2 deletions Lib/test/test_xml_etree.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,8 +370,7 @@ 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.assertRaisesRegex(ValueError,
r'Element\.remove\(.+\): element not found'):
with self.assertRaises(ValueError):
element.remove(subelement)
self.serialize_check(element, '<tag key="value" />') # 6
element[0:0] = [subelement, subelement, subelement]
Expand Down Expand Up @@ -2758,6 +2757,17 @@ def test_pickle_issue18997(self):
self.assertEqual(e2.tag, 'group')
self.assertEqual(e2[0].tag, 'dogs')

def test_remove_errors(self):
e = ET.Element('tag')
with self.assertRaisesRegex(ValueError,
r"<Element 'subtag'.*> not in <Element 'tag'.*>"):
e.remove(ET.Element('subtag'))
with self.assertRaisesRegex(TypeError,
r".*\bElement, not type"):
e.remove(ET.Element)
with self.assertRaisesRegex(TypeError,
r".*\bElement, not int"):
e.remove(1)

class BadElementTest(ElementTestCase, unittest.TestCase):

Expand Down
7 changes: 5 additions & 2 deletions Lib/xml/etree/ElementTree.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,12 +266,15 @@ def remove(self, subelement):
ValueError is raised if a matching element could not be found.

"""
# assert iselement(element)
try:
self._children.remove(subelement)
except ValueError:
# to align the error type with the C implementation
if isinstance(subelement, type) or not iselement(subelement):
raise TypeError('expected an Element, not %s' %
type(subelement).__name__) from None
# to align the error message with the C implementation
raise ValueError("Element.remove(x): element not found") from None
raise ValueError(f"{subelement!r} not in {self!r}") 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,2 @@
Improve errors for :meth:`Element.remove
<xml.etree.ElementTree.Element.remove>`.
3 changes: 1 addition & 2 deletions Modules/_elementtree.c
Original file line number Diff line number Diff line change
Expand Up @@ -1679,8 +1679,7 @@ _elementtree_Element_remove_impl(ElementObject *self, PyObject *subelement)
}

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

Expand Down
Loading