Set a new item in the tree, overwriting anything already present at that path. The given value either forms a new node of the tree or overwrites an existing item at that location. Parameters ---------- path item new_nodes_along_path
(
self,
path: str | NodePath,
item: Any,
new_nodes_along_path: bool = False,
allow_overwrite: bool = True,
)
| 572 | self.children = new_children |
| 573 | |
| 574 | def _set_item( |
| 575 | self, |
| 576 | path: str | NodePath, |
| 577 | item: Any, |
| 578 | new_nodes_along_path: bool = False, |
| 579 | allow_overwrite: bool = True, |
| 580 | ) -> None: |
| 581 | """ |
| 582 | Set a new item in the tree, overwriting anything already present at that path. |
| 583 | |
| 584 | The given value either forms a new node of the tree or overwrites an |
| 585 | existing item at that location. |
| 586 | |
| 587 | Parameters |
| 588 | ---------- |
| 589 | path |
| 590 | item |
| 591 | new_nodes_along_path : bool |
| 592 | If true, then if necessary new nodes will be created along the |
| 593 | given path, until the tree can reach the specified location. |
| 594 | allow_overwrite : bool |
| 595 | Whether or not to overwrite any existing node at the location given |
| 596 | by path. |
| 597 | |
| 598 | Raises |
| 599 | ------ |
| 600 | KeyError |
| 601 | If node cannot be reached, and new_nodes_along_path=False. |
| 602 | Or if a node already exists at the specified path, and allow_overwrite=False. |
| 603 | """ |
| 604 | if isinstance(path, str): |
| 605 | path = NodePath(path) |
| 606 | |
| 607 | if not path.name: |
| 608 | raise ValueError("Can't set an item under a path which has no name") |
| 609 | |
| 610 | if path.root: |
| 611 | # absolute path |
| 612 | current_node = self.root |
| 613 | _root, *parts, name = path.parts |
| 614 | else: |
| 615 | # relative path |
| 616 | current_node = self |
| 617 | *parts, name = path.parts |
| 618 | |
| 619 | if parts: |
| 620 | # Walk to location of new node, creating intermediate node objects as we go if necessary |
| 621 | for part in parts: |
| 622 | if part == "..": |
| 623 | if current_node.parent is None: |
| 624 | # We can't create a parent if `new_nodes_along_path=True` as we wouldn't know what to name it |
| 625 | raise KeyError(f"Could not reach node at path {path}") |
| 626 | else: |
| 627 | current_node = current_node.parent |
| 628 | elif part in ("", "."): |
| 629 | pass |
| 630 | elif part in current_node.children: |
| 631 | current_node = current_node.children[part] |