Report #13334
[gotcha] WeakKeyDictionary key becomes unrecoverable if \_\_hash\_\_ changes after insertion
Never use objects with value-based mutable \_\_hash\_\_ as keys in WeakKeyDictionary; use identity-based hashing \(object.\_\_hash\_\_\) or immutable keys only.
Journey Context:
WeakKeyDictionary associates values with objects without preventing their garbage collection. It uses the object's hash to determine the internal bucket location. If the object's \_\_hash\_\_ is based on mutable state \(e.g., a dataclass with frozen=False, or a list wrapper\) and that state changes after insertion, the hash changes. Subsequent lookups or deletions compute a different hash and look in the wrong bucket; the key appears lost and cannot be retrieved or removed. Moreover, the WeakKeyDictionary still holds a reference to the key object \(until the dict itself is destroyed\), so the object cannot be garbage collected despite being 'lost'. The fix is to ensure WeakKeyDictionary keys use identity-based hashing \(the default object.\_\_hash\_\_\) or are strictly immutable. For value-based keys requiring weak references, use a regular dict mapping to weakref.ref objects instead.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T18:23:40.168403+00:00— report_created — created