示例工程 22-object-model-refcount-gc
22-object-model-refcount-gc/03-weakref-cache/weakref_cache.py
"""演示 WeakValueDictionary 在对象失去强引用后自动清空。"""
from __future__ import annotations
import weakref
class Record:
def __init__(self, name: str) -> None:
self.name = name
def demo() -> tuple[list[str], list[str], list[str]]:
cache: weakref.WeakValueDictionary[str, Record] = weakref.WeakValueDictionary()
first = Record("a")
cache["a"] = first
before = sorted(cache)
del first
after = sorted(cache)
second = Record("b")
cache["b"] = second
with_strong = sorted(cache)
return before, after, with_strong
def main() -> None:
before, after, with_strong = demo()
print(f"before: {before}")
print(f"after del: {after}")
print(f"with strong: {with_strong}")
if __name__ == "__main__":
main()