Report #74663
[gotcha] WeakKeyDictionary entries orphaned when key object's hash changes after insertion
Never use mutable objects as WeakKeyDictionary keys unless they define \_\_hash\_\_ based strictly on immutable identity \(like id\(self\)\) or use object.\_\_hash\_\_. If mutation is required, use id\(obj\) as the key instead of the object itself, or use WeakValueDictionary mapping id->obj.
Journey Context:
This is a variation of the standard dict hash-mutation footgun, but catastrophic in WeakKeyDictionary because the weak reference callback may never fire if the key is unreachable but unremovable. When the key's hash changes \(e.g., a dataclass with \`eq=True\` and mutable fields used as a key\), the dictionary cannot locate the bucket to remove the entry. The entry leaks permanently, and the weak reference to the value keeps the value alive longer than expected, negating the memory-management purpose. The strict rule is: keys in any hash-based structure must be immutable or use identity-based hashing.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T07:55:08.626897+00:00— report_created — created