UserDict Intercepts Every Write And Read
UserDict routes every write and read through __setitem__ and __getitem__, so normalization and validation survive update(), construction, and setdefault too.
Code
from collections import UserDict
class LowerKeys(UserDict):
# Every write and read flows through these two hooks
def __setitem__(self, key, value):
if not isinstance(key, str):
raise TypeError(f"key must be str, got {type(key).__name__}")
super().__setitem__(key.lower(), value)
def __getitem__(self, key):
return super().__getitem__(key.lower())
quota = LowerKeys(maxThreads=8)
print("stored key:", list(quota.data))
print("read back:", quota["MAXTHREADS"])
quota["MAXTHREADS"] = 16
print("after overwrite:", quota["maxthreads"])
try:
quota[42] = "answer"
except TypeError as exc:
print("rejected:", exc)
# A plain dict subclass misses update()/setdefault() paths; UserDict routes
# every mutation through the same __setitem__ hooks
quota.update({"MAXMEMORY_MB": 512})
print("via update:", quota.data["maxmemory_mb"])Output
Captured from a sandboxed run of this snippet in the build pipeline.
stored key: ['maxthreads']
read back: 8
after overwrite: 16
rejected: key must be str, got int
via update: 512How the snippet works
UserDict Intercepts Every Write And Read reduces to the classes LowerKeys and misses and the functions __setitem__ and __getitem__.
Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.
What to watch for
- The guard
not isinstance(key, str)short-circuits the flow with an earlyraisewhen its condition holds.
Using it
The primary signature is def __setitem__(self, key, value)
Output lines are prefixed (stored key:, read back:, after overwrite:), making each step’s effect easy to spot.
Key statements
def __setitem__(self, key, value):
if not isinstance(key, str):
raise TypeError(f"key must be str, got {type(key).__name__}")
super().__setitem__(key.lower(), value)
def __getitem__(self, key):
return super().__getitem__(key.lower())
except TypeError as exc:
print("rejected:", exc)
Interactive Tools for This Topic
FAQ
- How does the code behave when input is bad?
- It throws `TypeError` before any real work runs, via the guard `not isinstance(key, str)` — handle it at the call site or let it propagate deliberately.
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Every import resolves inside the standard library — `collections`. The file defines `__setitem__`, `__getitem__` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.