Added indexed lists and link edition in tunes
This commit is contained in:
36
folkugat_web/model/_base.py
Normal file
36
folkugat_web/model/_base.py
Normal 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)
|
||||
Reference in New Issue
Block a user