Skip to content

Commit

Permalink
ENH: Add remove_from_tree (#1432)
Browse files Browse the repository at this point in the history
The remove_from_tree method can be used to remove an outline item

Fixes #1427
  • Loading branch information
pubpub-zz authored Nov 18, 2022
1 parent 56395e9 commit df933f2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
9 changes: 9 additions & 0 deletions PyPDF2/generic/_data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,15 @@ def remove_child(self, child: Any) -> None:

_reset_node_tree_relationship(child_obj)

def remove_from_tree(self) -> None:
"""
remove the object from the tree it is in
"""
if NameObject("/Parent") not in self:
raise ValueError("Removed child does not appear to be a tree item")
else:
cast("TreeObject", self["/Parent"]).remove_child(self)

def emptyTree(self) -> None: # pragma: no cover
deprecate_with_replacement("emptyTree", "empty_tree", "4.0.0")
self.empty_tree()
Expand Down
9 changes: 7 additions & 2 deletions tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,11 @@ def test_remove_child_not_in_that_tree():

tree = TreeObject()
tree.indirect_ref = NullObject()
child = ChildDummy(TreeObject())
# child = ChildDummy(TreeObject())
child = TreeObject()
with pytest.raises(ValueError) as exc:
child.remove_from_tree()
assert exc.value.args[0] == "Removed child does not appear to be a tree item"
tree.add_child(child, ReaderDummy())
with pytest.raises(ValueError) as exc:
tree.remove_child(child)
Expand Down Expand Up @@ -558,7 +562,8 @@ def test_remove_child_found_in_tree():
assert len([el for el in tree.children()]) == 3

# Remove middle child
tree.remove_child(child4)
# tree.remove_child(child4)
child4.remove_from_tree()
assert tree[NameObject("/Count")] == 2
assert len([el for el in tree.children()]) == 2

Expand Down

0 comments on commit df933f2

Please sign in to comment.