Created
August 29, 2026 19:59
-
-
Save mypy-play/39a7c002229f5abe94cc03f174b83d1b to your computer and use it in GitHub Desktop.
Shared via mypy Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import abc | |
| import collections.abc | |
| import logging | |
| import typing | |
| import uuid | |
| logger = logging.getLogger(__name__) | |
| class GenericRegistry[K, V](abc.ABC, collections.abc.Mapping[K, V]): | |
| _items: dict[K, V] | |
| def __init__(self) -> None: | |
| self._items = {} | |
| def add_item(self, key: K, value: V, overwrite: bool = False) -> None: | |
| logger.debug("%s added - key: %r, item: %r", self.item_type, key, value) | |
| if key in self._items: | |
| if not overwrite: | |
| message = ( | |
| f"{self.item_type} already exists - key: {key!r}, item: {value!r}" | |
| ) | |
| raise KeyError(message) | |
| logger.warning( | |
| "%s overwritten - key: %r, item: %r", self.item_type, key, value | |
| ) | |
| self._items[key] = value | |
| @property | |
| def item_count(self) -> int: | |
| return len(self) | |
| @property | |
| @abc.abstractmethod | |
| def item_type(self) -> str: | |
| raise NotImplementedError | |
| def remove_item(self, key: K) -> None: | |
| if key not in self._items: | |
| message = f"{self.item_type} does not exist with key: {key!r}" | |
| logger.error(message) | |
| del self._items[key] | |
| def __getitem__(self, key: K) -> V: | |
| return self._items[key] | |
| def __iter__(self) -> collections.abc.Iterator[K]: | |
| yield from self._items | |
| def __len__(self) -> int: | |
| return len(self._items) | |
| class UserRegistry(GenericRegistry[uuid.UUID, dict[str, typing.Any]]): | |
| @property | |
| def item_type(self) -> str: | |
| return "user" | |
| if __name__ == "__main__": | |
| logging.basicConfig(level=logging.DEBUG) | |
| registry = UserRegistry() | |
| user_id = uuid.uuid4() | |
| registry.add_item(user_id, {"name": "John Doe"}) | |
| try: | |
| registry.add_item(user_id, {}) | |
| except KeyError: | |
| pass | |
| else: | |
| raise AssertionError("didn't throw") | |
| registry.add_item(user_id, {"name": "John Smith"}, overwrite=True) | |
| print(registry.item_count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment