Object lifetime and weak references
Keep a lookup table for documents that are already open, without making the lookup table responsible for keeping them alive.
On this page
Read the model
A name refers to an object. Removing one name removes one reference. A normal dictionary holding the object as a value also holds a strong reference. A WeakValueDictionary instead lets a value disappear when no strong references keep it alive.
Follow the example
import gc
from weakref import WeakValueDictionary
class Document:
pass
opened = WeakValueDictionary()
doc = Document()
opened["notes"] = doc
alias = doc
del doc
print("notes" in opened)
del alias
gc.collect()
print("notes" in opened)The alias keeps the document alive after the original name is deleted. Membership is True at the first print. After deleting the alias and collecting garbage, the entry is gone, so the second print displays False. Weak references suit optional caches where a miss is acceptable.
Change one condition
Replace WeakValueDictionary() with {}. Now both checks print True. The dictionary itself owns a strong reference. For resources such as open files, use a with block to choose a predictable close time independently of object collection.