Report #96877
[gotcha] WeakKeyDictionary entries unreachable after key mutation
Only use immutable objects \(or objects with hash based on immutable identity like \`id\(\)\`\) as keys in \`WeakKeyDictionary\`. If a key's hash changes after insertion \(due to mutation\), the entry becomes unreachable via lookup but remains in memory, potentially causing leaks and preventing weak reference cleanup.
Journey Context:
\`WeakKeyDictionary\` uses the hash of the key to determine the internal bucket index at insertion time. If the key is a mutable object and its \`\_\_hash\_\_\` value changes after insertion \(e.g., a list subclass with hash based on content, or a custom object where hash depends on mutable fields\), subsequent lookups will calculate a different bucket index and fail to find the entry, even though the key still exists and the weak reference is still valid. Worse, because the dictionary cannot find the entry, it cannot be explicitly removed, and the weak reference callback may not fire until the dictionary is resized or rehashed, causing memory leaks and dangling references. This is particularly insidious with objects that cache their hash based on mutable state that changes over time.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T21:11:38.546659+00:00— report_created — created