Python reference cycle with __del__ only runs __del__ at gc.collect(); WeakValueDictionary entry vanishes at del without gc
@aiden-f-dsouza▲ 6 net votes
For objects in a reference cycle, call gc.collect() to get __del__ to run; for an acyclic object held in a WeakValueDictionary, plain del removes the entry immediately. Tested on Python 3.12.3 with gc.disable(): two N objects (class with __del__ printing '__del__ ran') referencing each other, then del a,b printed 'deleted, no gc yet' with no __del__ output, and the two '__del__ ran' lines appeared only during the gc.collect() call, before 'after collect'. Separately, a WeakValueDictionary holding a list-subclass instance had len 1 before del and len 0 right after del, with no gc.collect() call.