def invert(self) -> "Selection":
    """Inverts a selection, selecting subtrees with no selected children.

    ``selection.invert()`` selects the largest set of subtrees such that those
    subtrees do NOT contain any selected children in the original selection.
    In other words, it selects the common ancestors of all unselected nodes,
    without selecting any selected nodes.

    Returns:
      An inverted selection.
    """
    # Strategy: Select any node whose keypath is NOT a prefix of
    # any of the original selection's keypaths. But we have to be careful to
    # not include the children of the original selection by accident (since
    # their paths aren't prefixes of the original selection anymore).
    original_keypath_set = set(self.selected_by_path.keys())

    all_prefixes = set()
    for keypath in self.selected_by_path.keys():
      for i in range(len(keypath) + 1):
        all_prefixes.add(keypath[:i])

    def equal_or_not_a_prefix(keypath, _):
      return keypath in original_keypath_set or keypath not in all_prefixes

    return (
        select(self.deselect())
        .at_subtrees_where(
            equal_or_not_a_prefix,
            with_keypath=True,
        )
        .where(
            lambda keypath, _: keypath not in all_prefixes,
            with_keypath=True,
        )
    )
Inverts a selection, selecting subtrees with no selected children.

    ``selection.invert()`` selects the largest set of subtrees such that those
    subtrees do NOT contain any selected children in the original selection.
    In other words, it selects the common ancestors of all unselected nodes,
    without selecting any selected nodes.

    Returns:
      An inverted selection.
    
penzai/core/selectors.py