Python Glossary Русский

all Python 3weakrefterm

weakref.WeakValueDictionary

weak collections

A dict with weak values: an entry disappears once its value object is deleted. The basis of a cache that does not keep objects alive by itself.

Syntax

d = weakref.WeakValueDictionary()

A beginner's trap: d['k'] = Obj() — the entry vanishes at once, because nothing else refers to the new object. Such a cache keeps an object exactly as long as someone else needs it. Values must support weak references too: numbers, strings and lists cannot be stored. If you need to keep the last N objects regardless of use, that is functools.lru_cache, not this dict.

Examples

import weakref
class Image:
    pass
cache = weakref.WeakValueDictionary()
cache['tmp'] = Image()
print('tmp' in cache)  # → False
img = Image()
cache['logo'] = img
print('logo' in cache)  # → True
del img
print('logo' in cache)  # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy