Added indexed lists and link edition in tunes

This commit is contained in:
marc
2025-03-11 23:05:20 +01:00
parent efd26ce19d
commit a85efd0838
22 changed files with 498 additions and 137 deletions

View File

@@ -0,0 +1,36 @@
import dataclasses
from typing import Optional, TypeVar
@dataclasses.dataclass
class WithId:
id: Optional[int]
T = TypeVar("T", bound=WithId)
class IndexedList(list[T]):
def append(self, _item: T) -> None:
if _item.id is None:
_item.id = max((i.id or 0 for i in self), default=0) + 1
return super().append(_item)
def find_idx(self, _id: int) -> int:
try:
i, _ = next(filter(lambda it: it[1].id == _id, enumerate(self)))
except StopIteration:
raise ValueError(f"Could not find item with id {_id}")
return i
def get(self, _id: int) -> T:
i = self.find_idx(_id)
return self.__getitem__(i)
def delete(self, _id: int) -> None:
i = self.find_idx(_id)
return super().__delitem__(i)
def replace(self, _id: int, _obj: T) -> None:
i = self.find_idx(_id)
super().__setitem__(i, _obj)