import ast import builtins import sys import os def log(msg, write=os.write): msg = (msg + "\n").encode() write(1, msg) with open("func.py", encoding="ascii") as fp: source = fp.read() tree = ast.parse(source) class Cycle: def __del__(self): log("Cycle.__del__") a = Cycle() b = Cycle() a.b = b b.a = a a.ast = tree # Put the cycle somewhere to survive until the *last* GC collection def callback(*args): pass callback.a = a os.register_at_fork(after_in_child=callback) print("exit")