def _check_loop(self, new_parent: Tree | None) -> None:
        """Checks that assignment of this new parent will not create a cycle."""
        if new_parent is not None:
            if new_parent is self:
                raise InvalidTreeError(
                    f"Cannot set parent, as node {self} cannot be a parent of itself."
                )

            if self._is_descendant_of(new_parent):
                raise InvalidTreeError(
                    "Cannot set parent, as intended parent is already a descendant of this node."
                )
Checks that assignment of this new parent will not create a cycle.
xarray/core/treenode.py