from secrets import token_hex from dataclasses import dataclass import re @dataclass(frozen=True) class Span: trace: str span: str parent: str | None = None def child(parent=None): if parent is None: return Span(token_hex(16), token_hex(8)) if not re.fullmatch('[0-9a-f]{32}', parent.trace) or not re.fullmatch('[0-9a-f]{16}', parent.span): raise ValueError('invalid context') return Span(parent.trace, token_hex(8), parent.span) root = child() a, b = child(root), child(root) assert a.trace == b.trace == root.trace assert a.parent == root.span and a.span != b.span