- self.id_ = cursor.lastrowid
- cache = getattr(db_conn, f'cached_{table_name}')
- cache[self.id_] = self
+ self.id_ = cursor.lastrowid # type: ignore[assignment]
+ self.cache()
+
+ @classmethod
+ def get_cached(cls: type[T], id_: X) -> T | None:
+ """Get object of id_ from class's cache, or None if not found."""
+ # pylint: disable=consider-iterating-dictionary
+ if id_ in cls.cache_.keys():
+ obj = cls.cache_[id_]
+ assert isinstance(obj, cls)
+ return obj
+ return None
+
+ def cache(self) -> None:
+ """Update object in class's cache."""
+ if self.id_ is None:
+ raise HandledException('Cannot cache object without ID.')
+ self.__class__.cache_[self.id_] = self
+
+ def uncache(self) -> None:
+ """Remove self from cache."""
+ if self.id_ is None:
+ raise HandledException('Cannot un-cache object without ID.')
+ del self.__class__.cache_[self.id_]
+
+ @classmethod
+ def empty_cache(cls) -> None:
+ """Empty class's cache."""
+ cls.cache_ = {}