Skip to content

Instantly share code, notes, and snippets.

@ewheeler
Created June 18, 2025 14:05
Show Gist options
  • Save ewheeler/12fef1ed93febe5a59ba2fa76878d2a2 to your computer and use it in GitHub Desktop.
Save ewheeler/12fef1ed93febe5a59ba2fa76878d2a2 to your computer and use it in GitHub Desktop.
A Python dict that can report which keys you did not use
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.
from https://www.peterbe.com/plog/a-python-dict-that-can-report-which-keys-you-did-not-use
"""
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment