WeakValueDictionary Evicts Dead Values

WeakValueDictionary holds values weakly: entries disappear when the last strong reference dies, while live entries keep normal dict semantics like get.

PythonResilience

Code

pythonsnippet
26 lines
import weakref


class Session:
    def __init__(self, user):
        self.user = user


# WeakValueDictionary 的值是弱引用:没人再持有 Session 时条目自动消失
cache = weakref.WeakValueDictionary()

sess = Session('alice')
cache['alice'] = sess
print('stored     :', 'alice' in cache)

# 删除最后一个强引用:CPython 引用计数立即回收(无循环引用时),条目跟着消失
del sess
print('after del  :', 'alice' in cache, len(cache))

# 强引用保留期间条目稳定存在
keeper = Session('bob')
cache['bob'] = keeper
print('kept       :', cache['bob'].user)

# 运行时仍是 dict 语义:get/默认值照常工作
print('missing    :', cache.get('carol', 'no session'))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

stored     : True
after del  : False 0
kept       : bob
missing    : no session

Inside the snippet

Count the class Session and the function __init__ as the entire surface area of WeakValueDictionary Evicts Dead Values.

What to watch for

  • Nothing to install: weakref ships with the Python standard library.

Putting it to use

The primary signature is def __init__(self, user)

Expect labeled output — stored :, after del :, kept : — when the file runs.

Core lines

def __init__(self, user):
    self.user = user

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `__init__` at load time.