Comment

Michael Cook

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

Peter Bengtsson

Blog post updated, thanks to you! Thanks!

mataha

TypeVars shouldn't be necessary, you can do just:

from typing import TypeVar, Any

class TrackingDict[K, V](dict[K, V]):
    ...