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
13 changes: 13 additions & 0 deletions Lib/test/test_xml_etree.py
Original file line number Diff line number Diff line change
Expand Up @@ -2654,6 +2654,19 @@ def f():

class BasicElementTest(ElementTestCase, unittest.TestCase):

def test_reinit_releases_children(self):
# gh-153537: re-init should release the previous children.
e = ET.Element('a', {'k': 'v'})
children = [ET.SubElement(e, 'b') for _ in range(3)]
refs = [weakref.ref(c) for c in children]
del children
self.assertEqual(len(e), 3)
e.__init__('a')
gc_collect()
self.assertEqual(len(e), 0)
self.assertEqual(e.attrib, {})
self.assertTrue(all(ref() is None for ref in refs))

def test___init__(self):
tag = "foo"
attrib = { "zix": "wyp" }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Re-initializing an :class:`xml.etree.ElementTree.Element` in the C accelerator
now discards the previous children and attributes instead of leaking them,
matching the pure-Python implementation. Patch by tonghuaroot.
3 changes: 3 additions & 0 deletions Modules/_elementtree.c
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,9 @@ element_init(PyObject *self, PyObject *args, PyObject *kwds)

self_elem = (ElementObject *)self;

/* On re-init, drop any children and attrib from a previous init. */
clear_extra(self_elem);

if (attrib != NULL && !is_empty_dict(attrib)) {
if (create_extra(self_elem, attrib) < 0) {
Py_DECREF(attrib);
Expand Down
Loading