On this page
weakref.WeakKeyDictionary
Prev: weakref.ReferenceType | Up: weakref | Next: weakref.WeakMethod
Rel: weakref.CallableProxyType, weakref.finalize, weakref.getweakrefcount, weakref.getweakrefs
Ref: docs.python.org — weakref.WeakKeyDictionary
Tags: #public #python3 #stdlib #weakref
Import
import weakref
from weakref import WeakKeyDictionary
Signature & Overview
weakref.WeakKeyDictionary(dict=None)
Mapping class that references keys weakly.
Methods & Attributes
WeakKeyDictionary.clear(self)— D.clear() -> None. Remove all items from D.WeakKeyDictionary.copy(self)—WeakKeyDictionary.copymethod/property.WeakKeyDictionary.get(self, key, default=None)—WeakKeyDictionary.getmethod/property.WeakKeyDictionary.items(self)—WeakKeyDictionary.itemsmethod/property.WeakKeyDictionary.keyrefs(self)— Return a list of weak references to the keys.WeakKeyDictionary.keys(self)—WeakKeyDictionary.keysmethod/property.WeakKeyDictionary.pop(self, key, *args)—WeakKeyDictionary.popmethod/property.WeakKeyDictionary.popitem(self)—WeakKeyDictionary.popitemmethod/property.WeakKeyDictionary.setdefault(self, key, default=None)—WeakKeyDictionary.setdefaultmethod/property.WeakKeyDictionary.update(self, dict=None, /, **kwargs)—WeakKeyDictionary.updatemethod/property.WeakKeyDictionary.values(self)—WeakKeyDictionary.valuesmethod/property.
Usage
import weakref
class Node: pass
n = Node()
meta = weakref.WeakKeyDictionary({n: 'root'})
assert meta[n] == 'root'
del n
assert len(meta) == 0
Gotchas
- Keys must be weak-referenceable AND hashable: Great for attaching metadata to objects without preventing garbage collection.
REPL Inspect
from weakref import WeakKeyDictionary
help(WeakKeyDictionary)
Linked from
Related notes
- tuts/python3/stdlib_module/weakref/ReferenceType Linked here; links to this page; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/WeakMethod Linked here; links to this page; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/weakref/CallableProxyType Linked here; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/finalize Linked here; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/getweakrefcount Linked here; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/getweakrefs Linked here; shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/proxy shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/ProxyType shared tags: #stdlib, #weakref
- tuts/python3/stdlib_module/weakref/ref shared tags: #stdlib, #weakref