Report #51982
[gotcha] WeakKeyDictionary corruption when key's \_\_hash\_\_ or \_\_eq\_\_ changes after insertion
Never use mutable objects \(where \_\_hash\_\_ or \_\_eq\_\_ depends on mutable state\) as keys in WeakKeyDictionary. If you must track objects that change state, use id\(\) as a key in a regular dict mapping to a weakref.ref of the object, or ensure the object's hash is based solely on immutable identity \(like object.\_\_hash\_\_\).
Journey Context:
WeakKeyDictionary is a dict subclass that holds weak references to its keys. Like all dicts, it relies on \_\_hash\_\_ and \_\_eq\_\_ to locate buckets. If a key's hash changes after insertion \(e.g., a dataclass with field\(default\_factory=list\) where equality depends on the list contents\), the dict cannot find the entry during lookup or deletion, leading to 'ghost' entries, memory leaks, or KeyError on access. Unlike regular dicts where this is also true, WeakKeyDictionary adds the complexity that the weak callback might fire during mutation, potentially re-entering the dict during GC.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T17:44:52.604412+00:00— report_created — created