from dataclasses import dataclass, field from typing import TypeVar from cross.attachments import Attachment from cross.fragments import Fragment T = TypeVar("T", bound=Attachment) class AttachmentKeeper: def __init__(self) -> None: self._map: dict[type, Attachment] = {} def put(self, attachment: Attachment) -> None: self._map[attachment.__class__] = attachment def get(self, cls: type[T]) -> T | None: instance = self._map.get(cls) if instance is None: return None if not isinstance(instance, cls): raise TypeError(f"Expected {cls.__name__}, got {type(instance).__name__}") return instance def __repr__(self) -> str: return f"AttachmentKeeper(_map={self._map.values()})" @dataclass class Post: id: str parent_id: str | None text: str # utf-8 text attachments: AttachmentKeeper = field(default_factory=AttachmentKeeper) fragments: list[Fragment] = field(default_factory=list)