Walk down a docutils node tree by repeatedly indexing children. Returns a Node (could be Element, Text, etc.) Example:: extract_node(doc, 0, 2, 1) == doc[0][2][1]
(node: Node, /, *indices: int)
| 141 | |
| 142 | |
| 143 | def extract_node(node: Node, /, *indices: int) -> Node: |
| 144 | """Walk down a docutils node tree by repeatedly indexing children. |
| 145 | |
| 146 | Returns a Node (could be Element, Text, etc.) |
| 147 | |
| 148 | Example:: |
| 149 | |
| 150 | extract_node(doc, 0, 2, 1) == doc[0][2][1] |
| 151 | """ |
| 152 | current: Node = node |
| 153 | |
| 154 | for depth, i in enumerate(indices): |
| 155 | path = ''.join(f'[{i}]' for i in indices[:depth]) |
| 156 | assert isinstance(current, nodes.Element), ( |
| 157 | f'Expected node{path} (at depth {depth}) to be an Element ' |
| 158 | f'before indexing with [{i}], got {type(current).__name__!r}' |
| 159 | ) |
| 160 | try: |
| 161 | current = current[i] |
| 162 | except IndexError as exc: |
| 163 | msg = ( |
| 164 | f'Index {i} out of range for node{path} (at depth {depth}) ' |
| 165 | f'for {type(current).__name__!r}' |
| 166 | ) |
| 167 | raise AssertionError(msg) from exc |
| 168 | |
| 169 | return current |
| 170 | |
| 171 | |
| 172 | def extract_element(node: Node, /, *indices: int) -> Element: |
searching dependent graphs…