weakref.WeakKeyDictionary()
Performance Patterns

Meaning

A mapping that holds weak references to its keys, allowing entries to be automatically removed when the key object is no longer strongly referenced elsewhere.

Primary Function

Provides a dictionary‑like container that does not prevent its keys from being garbage‑collected, enabling automatic cleanup of cached associations.

Communicative Purpose

Expresses a weak‑key mapping for caching, observer patterns, or any scenario where associating data with objects must not impede their reclamation.

Pattern

WeakKeyDictionary([iterable])

Core Structure

WeakKeyDictionary([iterable]) → a mapping that holds weak references to its keys; entries disappear automatically when the key is garbage‑collected.

Função primária

Provides a dictionary‑like container that does not prevent its keys from being garbage‑collected, enabling automatic cleanup of cached associations.

Propósito comunicativo

Expresses a weak‑key mapping for caching, observer patterns, or any scenario where associating data with objects must not impede their reclamation.

Situações de gatilho

When you need to attach auxiliary data to objects that may be destroyed elsewhere (e.g., caching attributes of objects, listener callbacks, observer patterns) without causing memory leaks.

Contextos

Used in caching frameworks, GUI toolkits for listener lists, object‑attribute caches, weak‑referencing libraries, and any scenario where objects should be allowed to die while cleaning up associated metadata.

Padrão

WeakKeyDictionary([iterable])

Estrutura central

WeakKeyDictionary([iterable]) → a mapping that holds weak references to its keys; entries disappear automatically when the key is garbage‑collected.

Slots de substituição

[initial_mapping]

Colocados típicos

  • weakref.ref
  • weakref.WeakValueDictionary
  • weakref.finalize
  • weakref.getweakcount
  • weakref.WeakSet

Substituições comuns

  • dict with manual cleanup (e.g.
  • using weakref callbacks)
  • weakref.WeakValueDictionary (weak values instead of weak keys)
  • functools.lru_cache for simple caching
  • weakref.WeakSet for tracking objects without associated data

Erros comuns

Assuming that values are also weakly held – they are not; only keys are weak, leading to unintended retention of values. Storing mutable objects as keys that may change hash after insertion, causing lookup failures because the weak reference still refers to the mutated object. Failing to handle missing keys after the key has been garbage‑collected, resulting in KeyError if .get() or try/except is not used. Confusing WeakKeyDictionary with WeakValueDictionary, which weakens values instead of keys and can cause unexpected memory retention. Creating a WeakKeyDictionary with a non‑hashable object as a key, which raises TypeError just like a regular dict.

Similar / contraste

WeakValueDictionary – holds weak references to values instead of keys. WeakSet – a set that holds weak references to its elements, useful for tracking objects without associated data. weakref.ref – a low‑level weak reference to a single object, used when a callback upon reclamation is needed. strong dict (dict) – retains keys strongly, preventing garbage collection. functools.lru_cache – a strong‑reference caching decorator that evicts based on usage, not object lifetime.

Interferências

Coming from Java: may expect WeakHashMap‑like behavior for both keys and values; in Python WeakKeyDictionary only weakens keys – use WeakValueDictionary for weak values. Coming from C++: may rely on RAII‑style cleanup; in Python you must rely on weakref callbacks or weak containers to avoid leaks. Coming from JavaScript: may assume objects are automatically cleaned when no longer referenced; remember that reference cycles still prevent collection unless broken via weak references.

Família do chunk

  • weakref.WeakValueDictionary
  • weakref.WeakSet
  • weakref.ref
  • weakref.finalize

Nuance

Do not use when you need to keep the associated data alive as long as the key lives; the value is held strongly and survives even after the key is reclaimed. Performance impact is minimal; the overhead is a weak reference per entry, negligible compared to the cost of a strong reference. Be aware that iterating over a WeakKeyDictionary while keys are being garbage‑collected can raise RuntimeError if the dictionary changes size during iteration; iterate over a copy or use .items() safely.

Efeito pragmático

Enables automatic cleanup of cached data, preventing memory leaks in caches, observer lists, and other auxiliary data structures, thereby improving long‑term memory efficiency of long‑running applications.

Dica de memória

Think of a WeakKeyDictionary as a sticky note that only sticks to the object while the object is still alive; once the object is thrown away, the note falls off automatically.

Nota

WeakKeyDictionary requires its keys to be hashable; the weak reference does not affect hashability.

Upgrade path

Consider using weakref.WeakValueDictionary when you need weak values, or functools.lru_cache for simple LRU caching, or weakref.WeakSet for tracking objects without associated data.

Tipo de construção: InstantiationTag de espaçamento: Medium-term

Log in to save chunks.