⬅︎ Back to A Python dict that can report which keys you did not use
Blog post updated, thanks to you! Thanks!
How about this? from typing import TypeVar, Any K = TypeVar('K') V = TypeVar('V') class TrackingDict(dict[K, V]): """ A `dict` that keeps track of which keys are accessed. """ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self._accessed_keys: set[K] = set() def __getitem__(self, key: K) -> V: self._accessed_keys.add(key) return super().__getitem__(key) @property def accessed_keys(self) -> set[K]: return self._accessed_keys @property def never_accessed_keys(self) -> set[K]: return set(self.keys()) - self._accessed_keys
TypeVars shouldn't be necessary, you can do just:from typing import TypeVar, Anyclass TrackingDict[K, V](dict[K, V]): ...
Comment
Blog post updated, thanks to you! Thanks!
Parent comment
How about this? from typing import TypeVar, Any K = TypeVar('K') V = TypeVar('V') class TrackingDict(dict[K, V]): """ A `dict` that keeps track of which keys are accessed. """ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self._accessed_keys: set[K] = set() def __getitem__(self, key: K) -> V: self._accessed_keys.add(key) return super().__getitem__(key) @property def accessed_keys(self) -> set[K]: return self._accessed_keys @property def never_accessed_keys(self) -> set[K]: return set(self.keys()) - self._accessed_keys
Replies
TypeVars shouldn't be necessary, you can do just:
from typing import TypeVar, Any
class TrackingDict[K, V](dict[K, V]):
...