from weakref import WeakValueDictionary import _thread, gc, time def f(): while True: time.sleep(0.01) gc.collect() class C: pass class D: pass d = WeakValueDictionary() _thread.start_new_thread(f, ()) while True: x = d.setdefault(10, D()) assert x is not None # we never put None in there! tp = x.__class__ del x if tp is D: c = C(); c.cycle = c d[10] = c c = None