How can I intentionally leak an object, so that it will never ever be garbage collected?

Viewed 113

Here's a weird problem: I want to intentionally leak a Python object, and all the objects it references. I want them to become immortal. And most importantly, I want to guarantee that their finalizer / __del__ methods will never run. (The motivation is related to an exotic issue around fork-safety that I won't go into here. fork is the worst, but we're stuck with it.)

What's the simplest way to reliably do that? I can save a reference to it in a module global variable, but the interpreter can and might garbage collect module-globals when the program is shutting down, right?

I think it would work to spawn a thread with daemon=True that holds a reference to the object on its stack and just sleeps forever, but this is pretty weird and seeing this random thread will confuse people using debuggers.

On CPython, I could use a ctypes hack to manually increment the object's reference count, but that won't work on other interpreters like PyPy.

What's the most portable, reliable, cleanest way to accomplish this ugly goal?

(I only care about Python 3.5+, in case that affects anything.)

0 Answers
Related