How to Link Parent and Child Span Elements in Python

This code defines a lightweight mock element class and a function that links child elements to a parent when their ranges are nested within the parent's range.

Easy Python 3.9+ Aug 9, 2026 Observability & SRE 14 views 0 copies

Python code

33 lines
Python 3.9+
class MockElement:
    def __init__(self, name, start, end, children=None):
        self.name = name
        self.start = start
        self.end = end
        self.children = children or []

    def __repr__(self):
        return f"MockElement({self.name}, {self.start}-{self.end})"


def link_parent_child(parent, child):
    """Link a child element to its parent if spans overlap or are nested."""
    if child.start >= parent.start and child.end <= parent.end:
        parent.children.append(child)
        return True
    return False


if __name__ == "__main__":
    parent = MockElement("div", 0, 10)
    child1 = MockElement("p", 2, 5)
    child2 = MockElement("span", 6, 8)
    child3 = MockElement("h1", -1, 3)  # invalid overlap

    results = {
        "child1_linked": link_parent_child(parent, child1),
        "child2_linked": link_parent_child(parent, child2),
        "child3_linked": link_parent_child(parent, child3),
    }

    print("Link results:", results)
    print("Parent children:", parent.children)

Output

stdout
Link results: {'child1_linked': True, 'child2_linked': True, 'child3_linked': False}
Parent children: [MockElement(p, 2-5), MockElement(span, 6-8)]

How it works

The MockElement class stores a name and start/end positions to represent a span. The link_parent_child function checks if the child's span is fully contained within the parent's span using start and end comparisons. If the condition holds, the child is appended to the parent's children list and True is returned; otherwise False. This provides a simple containment check useful for building hierarchical structures from flat span data. The example demonstrates correct linking for nested spans and rejects an out-of-range child.

Common mistakes

  • Using half-open intervals inconsistently (assuming start is inclusive but end exclusive) without defining it clearly.
  • Not considering overlapping but non-nested spans that should be siblings, not parent-child.
  • Forgetting that this function mutates the parent's children list, which may have side effects in larger code.

Variations

  1. Use a dataclass with slots for better performance when handling many elements.
  2. Implement a function that returns a new tree instead of mutating the parent in place.

Real-world use cases

  • Building nested HTML element trees from flat parsed markup where each tag has offsets.
  • Validating that child components' layout ranges fit within parent containers in UI testing mocks.
  • Organizing log spans into parent-child relationships for trace or span visualization.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Observability & SRE

Related tutorials and quizzes for this topic.