Python Glossary Русский

all Python 3weakrefterm

weakref.WeakKeyDictionary

weak collections

A dict with weak keys: an entry disappears once its key object is deleted. It attaches data to other objects without changing them or keeping them alive.

Syntax

d = weakref.WeakKeyDictionary()

Only objects that support weak references can be keys — strings and numbers do not (TypeError), so it is useless as a cache keyed by strings. Keys are compared with ==, not by identity: two equal objects share one entry. Iterating while keys are being freed elsewhere is risky — the size may change mid-loop; iterate over a copy, list(d.items()).

Examples

import weakref
class Widget:
    pass
meta = weakref.WeakKeyDictionary()
w = Widget()
meta[w] = 'blue'
print(len(meta))  # → 1
del w
print(len(meta))  # → 0
try:
    meta['name'] = 1
except TypeError:
    print('TypeError')  # → TypeError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy