Ensure the Tree's internal tracker gets updated on node delete

See #2462.
This commit is contained in:
Dave Pearson
2023-05-08 09:15:28 +01:00
parent 1d985abf26
commit 2c39f50150

View File

@@ -352,6 +352,18 @@ class TreeNode(Generic[TreeDataType]):
class RemoveRootError(Exception): class RemoveRootError(Exception):
"""Exception raised when trying to remove a tree's root node.""" """Exception raised when trying to remove a tree's root node."""
def _remove(self) -> None:
"""Remove the current node and all its children.
Note:
This is the internal support method for `remove`.
"""
for child in reversed(self._children):
child._remove()
assert self._parent is not None
del self._parent._children[self._parent._children.index(self)]
del self._tree._tree_nodes[self.id]
def remove(self) -> None: def remove(self) -> None:
"""Remove this node from the tree. """Remove this node from the tree.
@@ -360,8 +372,7 @@ class TreeNode(Generic[TreeDataType]):
""" """
if self.is_root: if self.is_root:
raise self.RemoveRootError("Attempt to remove the root node of a Tree.") raise self.RemoveRootError("Attempt to remove the root node of a Tree.")
assert self._parent is not None self._remove()
del self._parent._children[self._parent._children.index(self)]
self._tree._invalidate() self._tree._invalidate()